3

I've got the following code http://jsfiddle.net/yc7sj3pt/2/

document.getElementById('obj_one').addEventListener('mouseover', function(){
    var e = document.createEvent('HTMLEvents');
    e.initEvent('mouseover', true, false);

    document.getElementById('obj_two').dispatchEvent(e);
    console.log('hover');
}, false);

I'm trying to make the #obj_two react to hover (thus changing to color red) when I mouseover on #obj_one, but it is not working. What am I doing wrong?

gespinha
  • 7,968
  • 16
  • 57
  • 91

1 Answers1

5

According to this answer, you can't:

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.

The recommended approach instead is to add and remove a class on the mouseover and mouseout events, which I've done in this jsfiddle.

James Brierley
  • 4,630
  • 1
  • 20
  • 39
  • Thanks, it seems I should stick to this solution then. Sometimes best practices need to come first! – gespinha Sep 03 '15 at 19:17
  • "add and remove a class on the mouseover and mouseout events" ? or adding and removing a class from *elements*...? – Nir O. Sep 23 '20 at 11:19