How to Simulate a Mouseover in Pure JavaScript That Activates the CSS ":Hover"

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

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.

Is there any way to simulate onmouseover in Developer Tools?

You can use dispatch to send / fire an event for an element: element.dispatchEvent(event);. The support may vary on different browsers and versions; my demo on jsfiddle worked on chrome 65.

Given this html

<div id="menu">
<h3>Menu</h3>
<div>Sample to fire onmouseover using a script</div>
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
<button onclick="simulateMouseOver()">simulate onMouseOver</button>

Below an onmouseover-event is set for <div id=menu>. As soon as the mouse is moved over the div the event fires:

var menu =  document.getElementById("menu");
menu.addEventListener("mouseover", function(event){

event.target.style.backgroundColor = "blue";
setTimeout(function() {
event.target.style.backgroundColor = "";
}, 500);
}, false)();

To raise the onmouseover-event from inside a script you

  1. first have to create the correct event
  2. an then fire / dispatch this event to the target-element

See this code

function simulateMouseOver() {
var listItems = document.querySelectorAll("ul li")
var item1 = listItems.item(1);
var event = new MouseEvent('mouseover',
{view: window, bubbles: true, cancelable: true});

var cancelled = !item1.dispatchEvent(event);
if (cancelled) {
// a handler called preventDefault.

} else {
// none of the handlers called preventDefault.

}
}

You can find out more at

  • MDN dispatch event
  • MDN event mouseover

The question simulate a mouse click from 2011 or Trigger events in javascript from 2010 may be of use regarding the support in older browsers.

Hover over an element using JavaScript?

You first need to create an Event and then dispatch that on your required DOM element.

Here is how to create on mouseover event

var event = new MouseEvent('mouseover', {
'view': window,
'bubbles': true,
'cancelable': true
});

Then add an eventListener to your element yourself.

yourelement = document.querySelector('css selector here');
yourelement.addEventListener('mouseover', function() {
//something here
});

...and then finally dispatchEvent

yourelement.dispatchEvent(event);

I hope it works for whatever you're trying to achieve!
Cheers!

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

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.

Trigger css hover with JS

I know what you're trying to do, but why not simply do this:

$('div').addClass('hover');

The class is already defined in your CSS...

As for you original question, this has been asked before and it is not possible unfortunately.
e.g. http://forum.jquery.com/topic/jquery-triggering-css-pseudo-selectors-like-hover

However, your desired functionality may be possible if your Stylesheet is defined in Javascript. see:
http://www.4pmp.com/2009/11/dynamic-css-pseudo-class-styles-with-jquery/

Hope this helps!

How to trigger CSS hover state using Javascript?

If you could accept using :focus instead of hover, you can use:

var links = document.getElementsByTagName('a');
links[0].focus();

JS Fiddle demo.

Or

var linkToFocus = document.getElementById('link');
linkToFocus.focus();

JS Fiddle demo.

This approach, obviously, requires adapting your CSS to include the a:focus style:

a:link, a:visited {
background-color: #fff;
}
a:hover, a:focus, a:active {
background-color: #f00;
}

Javascript has methods to simulate user interactions like .click(), .focus(), .blur(). But no .hover(). Can JS simulate a hover / mouseover?

This appears not to be widely documented across the web, but it is possible to computationally simulate a human moving a mouse pointer over an element in the same way that element.click() simulates a human clicking on an element.

The correct approach is to use:

eventTarget.dispatchEvent(event)

in combination with a JS-native event.

Most references to dispatchEvent() involve a custom-written event, but, to reiterate, it is possible to use a JS-native event - in this case mouseover.

So... instead of the following, utilising the .click() method:

clickButton.addEventListener('click', () => square.click(), false);

We can deploy:

clickButton.addEventListener('click', () => {

let hover = new Event('mouseover');
square.dispatchEvent(hover);

}, false);

Working Example:

const square = document.getElementsByClassName('square')[0];
const clickSquare = () => {
event.target.dataset.receivedAction = 'click'; event.target.innerHTML = '<p>I\'ve been clicked!</p>';}
const hoverSquare = () => {
event.target.dataset.receivedAction = 'hover'; event.target.innerHTML = '<p>I\'ve been hovered over!</p>';}
const clearSquare = () => {
square.removeAttribute('data-received-action'); square.innerHTML = '';}
square.addEventListener('mouseover', hoverSquare, false);square.addEventListener('click', clickSquare, false);
const clickButton = document.querySelector('[data-deliver-action="click"]');const hoverButton = document.querySelector('[data-deliver-action="hover"]');const clearButton = document.querySelector('[data-deliver-action="clear"]');
clickButton.addEventListener('click', () => square.click(), false);
hoverButton.addEventListener('click', () => {
let hover = new Event('mouseover'); square.dispatchEvent(hover);
}, false);
clearButton.addEventListener('click', clearSquare, false);
.square {display: block;width: 120px;height: 120px;margin: 12px 6px;text-align: center;font-family: arial, helvetica, sans-serif;font-weight: bold;font-size: 14px;text-transform: uppercase;overflow: hidden;cursor: pointer;}
button {display: block;width: 160px;margin: 6px;cursor: pointer;}
.square {color: rgb(255, 0, 0);background-color: rgb(255, 0, 0);}
.square[data-received-action="click"] {background-color: rgb(255, 255, 0);}
.square[data-received-action="hover"] {color: rgb(255, 255, 255);background-color: rgb(255, 125, 0);}
<div class="square" tabindex="0"></div>
<button type="button" data-deliver-action="click">Click the Square</button><button type="button" data-deliver-action="hover">Hover over the Square</button><button type="button" data-deliver-action="clear">Clear Square</button>


Related Topics



Leave a reply



Submit