2

As titled, how do I trigger an onmouseover event on element in javascript? please refer to Code Snippet. Instead of hovering over the big box, can I click on the small black box and execute the onmouseover event? The goal is NOT to turn the box blue but TRIGGER the onmouseover event. And also I need this to be done with only JavaScript, no Jquery please.

function showBlue() {
	document.getElementById('xyz').style.background = "#425dff"; 
}
function showRed() {
	document.getElementById('xyz').style.background = "#e2e2e2";
}
#abc{width: 50px; height: 50px; background: #000000; color:#ffffff; cursor: pointer;}
#xyz{width: 200px; height: 200px; background: #e2e2e2;}
<div id="abc"><a>click me</a></div>

</br>

<div id="xyz" onmouseover="showBlue()" onmouseout="showGrey()"></div>

I tried this but did not work for me :(

<script>
    document.getElementById('abc').addEventListener("click", triggerFunction);

    function triggerFunction() {
        document.getElementById('xyz').mouseover();
    }
</script>
2
  • I need it to be a pure javascript solution if possible Commented Mar 13, 2015 at 18:56
  • I wish I could downvote that comment Teemu :( Commented Mar 13, 2015 at 18:56

2 Answers 2

3

This should work:

function showBlue() {
	document.getElementById('xyz').style.background = "#425dff"; 
}
function showGrey() {
	document.getElementById('xyz').style.background = "#e2e2e2";
}
function triggerMouseOver() {
    document.getElementById('xyz').onmouseover();
}
#abc{width: 50px; height: 50px; background: #000000; color:#ffffff; cursor: pointer;}
#xyz{width: 200px; height: 200px; background: #e2e2e2;}
<div id="abc" onclick="triggerMouseOver()"><a>click me</a></div>

</br>

<div id="xyz" onmouseover="showBlue()" onmouseout="showGrey()"></div>

You could also simply do this:

<div id="abc" onclick="document.getElementById('xyz').onmouseover()"><a>click me</a></div>
Sign up to request clarification or add additional context in comments.

3 Comments

Your element uses showGrey, but you've only declared showBlue and showRed. I think the showRed function needs renamed?
This would work with inline handlers only ...
Yes, his code had that wrong name but I forgot to fix it. I will update my answer code.
1

It should be onmouseover() instead of mouseover()

document.getElementById('xyz').onmouseover();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.