Javascript - programmatically invoking events

前端 未结 2 849
[愿得一人]
[愿得一人] 2020-12-11 22:45

Say I add events to an object using either addEventListener or attachEvent (depending on the browser); is it possible to later invoke those events programmatically?

相关标签:
2条回答
  • 2020-12-11 23:33

    Can you not create functions that do the work required, run those from the events then run those same functions later when required?

    0 讨论(0)
  • 2020-12-11 23:46

    As usual, you have to do it one way for Internet Explorer, and the correct way for everything else ;-)

    For IE:

    document.getElementById("thing_with_mouseover_handler").fireEvent("onmouseover");
    

    See the MSDN library for more info.

    For the real browsers:

    var event = document.createEvent("MouseEvent");
    event.initMouseEvent("mouseover", true, true, window);
    document.getElementById("thing_with_mouseover_handler").dispatchEvent(event);
    

    Note that, although the second, standards-based approach seems more long-winded, it is also considerably more flexible: check the documentation, starting with the Mozilla DOM Event Reference at https://developer.mozilla.org/en/DOM/event

    Although only tangentially related to what you're trying to do (it's related to custom events, rather than normal ones) Dean Edwards has some example code at http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ that may be worth a look.

    0 讨论(0)
提交回复
热议问题