javascript - dispatchEvent 'mouseover' not working - Stack Overflow

I've got the following code document.getElementById('obj_one').addEventListener('m

I've got the following code /

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?

I've got the following code http://jsfiddle/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?

Share Improve this question edited Sep 3, 2015 at 16:48 gespinha asked Sep 3, 2015 at 16:43 gespinhagespinha 8,50717 gold badges59 silver badges96 bronze badges 2
  • Why not add a class and do the styling that way instead? – James Brierley Commented Sep 3, 2015 at 16:48
  • @JamesBrierley I understand that solution, I wanted to do it too, but unfortunately I can't – gespinha Commented Sep 3, 2015 at 16:48
Add a ment  | 

1 Answer 1

Reset to default 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 remended approach instead is to add and remove a class on the mouseover and mouseout events, which I've done in this jsfiddle.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744193151a4562529.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信