Search code examples
javascripthtmlcsstriggersonmouseover

how to trigger an onmouseover event on element in javascript?


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>

Solution

  • 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>