Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger onmouseover event programmatically in JavaScript

Is there a way to programmatically trigger the onmouseover event in plain JavaScript? or "extract" the method from the onmouseover event to call it directly?

eg

<div id="bottom-div" onmouseover="myFunction('some param specific to bottom-div');">
    <div id="top-div" onmouseover="????????"></div>
</div>

top-div is above bottom-div, so the onmouseover won't get fired in bottom-div. i need a way of calling myFunction('some param specific to bottom-div'); from top-div

like image 591
fearofawhackplanet Avatar asked Feb 09 '10 10:02

fearofawhackplanet


People also ask

What is onmouseover in Javascript?

The onmouseover event occurs when the mouse pointer is moved onto an element, or onto one of its children. Tip: This event is often used together with the onmouseout event, which occurs when a user moves the mouse pointer out of an element.

What is the difference between mouseover and Mouseenter?

The mouseover event triggers when the mouse pointer enters the div element, and its child elements. The mouseenter event is only triggered when the mouse pointer enters the div element. The onmousemove event triggers every time the mouse pointer is moved over the div element.

How does mouseover event work?

The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves. These events are special, because they have property relatedTarget . This property complements target . When a mouse leaves one element for another, one of them becomes target , and the other one – relatedTarget .


3 Answers

const mouseoverEvent = new Event('mouseover');

whateverElement.dispatchEvent(mouseoverEvent);
like image 130
givehug Avatar answered Oct 17 '22 19:10

givehug


This worked for me in IE9 at least. Should be cross-browser compatible or close to it...

function FireEvent( ElementId, EventName )
{
    if( document.getElementById(ElementId) != null )    
    {   
        if( document.getElementById( ElementId ).fireEvent ) 
        {
            document.getElementById( ElementId ).fireEvent( 'on' + EventName );     
        }
        else 
        {   
            var evObj = document.createEvent( 'Events' );
            evObj.initEvent( EventName, true, false );
            document.getElementById( ElementId ).dispatchEvent( evObj );
        }
    }
}

For onmouseover example, call the function like this

FireEvent( ElementId, "mouseover" );
like image 32
Jonathan Avatar answered Oct 17 '22 17:10

Jonathan


For me following worked:

​document.getElementById('xyz').dispatchEvent(new MouseEvent('mouseover', { 'bubbles': true }));

Also:

​document.getElementById('xyz').dispatchEvent(new MouseEvent('mouseover', { 'view': window, 'bubbles': true, 'cancelable': true }));
like image 25
Kishan Avatar answered Oct 17 '22 17:10

Kishan