126
131

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでjQueryを使わずにイベントをtriggerする

Last updated at Posted at 2015-06-10

基本的なことなのですが、すぐ忘れるので。。。

JavaScriptでDOMノードの任意のイベントを発火するには以下の様にします。

function triggerEvent(element, event) {
   if (document.createEvent) {
       // IE以外
       var evt = document.createEvent("HTMLEvents");
       evt.initEvent(event, true, true ); // event type, bubbling, cancelable
       return element.dispatchEvent(evt);
   } else {
       // IE
       var evt = document.createEventObject();
       return element.fireEvent("on"+event, evt)
   }
}

例えば、mouseoverイベントをトリガーしたければ、以下のようにします。

HTML

<a id="the_link" href="http://google.com">google</a>

JavaScript

var a = document.getElementById("the_link");
triggerEvent(a, 'mouseover');

おまけ

clickイベントを発火したいときはもっと簡単です。上みたいなtriggerEventメソッドを使う必要はなく

var a = document.getElementById("the_link");
a.click();

で大丈夫です。

126
131
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
126
131

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?