Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I simulate a mouseover in pure JavaScript that activates the CSS ":hover"?

I've been trying to find code to simulate mouseover in Chrome but even though the "mouseover" listener gets fired, the CSS "hover" declaration is never set!

I tried also doing:

//Called within mouseover listener theElement.classList.add("hover"); 

But nothing seems to change the element to what is declared in its hover declaration.

Is this possible?

like image 958
Don Rhummy Avatar asked Jun 21 '13 02:06

Don Rhummy


2 Answers

You can't. It's not a trusted event.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

You have to add a class and add/remove that on the mouseover/mouseout events manually.

like image 94
Benjamin Gruenbaum Avatar answered Oct 01 '22 17:10

Benjamin Gruenbaum


You can simulate the mouseover event like this:

HTML

<div id="name">My Name</div> 

JavaScript

var element = document.getElementById('name'); element.addEventListener('mouseover', function() {   console.log('Event triggered'); });  var event = new MouseEvent('mouseover', {   'view': window,   'bubbles': true,   'cancelable': true });  element.dispatchEvent(event); 
like image 40
andresscode Avatar answered Oct 01 '22 18:10

andresscode