jQueryの .on('hover',function(){...}) ではhoverのイベントが動作しないのはなぜ?


  • 公開:
  • 更新:
  • 編集:
概要 ▶ .onのイベントを指定する引数部分に「hover」と書いても意図した動作にはなりません。それはhover自体が複数のイベントをまとめて書いた省略形(エイリアス)だからです。

jQuery .hover()

画像出典:.hover()(jQuery API Documentation)


●jQuery 1.7以降の.onを使っていますか?

jQueryの1.7以降では、.onという要素にイベントを追加する命令(メソッド)が使えるようになっています。今まで.bindで書いていたものから置き換えて使えるようです。

といっても私は.bindすら使っていませんでしたが…(.hover()や.click()だけで事足りていたので…)。

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()

.on() | jQuery API Documentation


.onの詳しい話は「jQuery の on() と off() を理解する(tacamy.blog)」に書かれているので、詳しく知りたい方はそちらを読んで欲しいのですが、.onは引数のひとつめにイベントを複数書けるのでとても簡単な書き方になります。便利そうですよね。

on() のひとつ目の引数を、スペース区切りで複数指定することで、どのイベントが発生しても同じ処理をさせることができます。

$('.foo').on('click blur', function(){...});

jQuery の on() と off() を理解する - tacamy.blog


●hoverをイベントとして引数に書いても反応しない

ということで、早速使ってみようと思いました。

$(".foo").on("click",function(){...});

とclickイベントが付いている要素へ、追加でマウスカーソルが要素に掛かっても(要素にホバーしても) function(){...} を実行できるようにしようと、

$(".foo").on("click hover",function(){...});

と書いたら動作しないわけですよ。


いつもマウスカーソルが要素に掛かる(ホバーする)時には次のように書いていて、

$(".foo").hover(function(){...});

これが動作するのになぜ…と思ったら、重大な勘違いをしていました。

●.hoverの中身はmouseenter+mouseleave

jQueryのページに書いてあるのですが、.hover(function(){...})は、.mouseenter(function(){...}).mouseleave(function(){...})の省略形(エイリアス)とのことです。つまりイベントを指定する本来の書き方ではないということです。

The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

Calling $( selector ).hover( handlerIn, handlerOut ) is shorthand for:

$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

See the discussions for .mouseenter() and .mouseleave() for more details.

.hover() | jQuery API Documentation


ということがわかれば簡単ですね。.fooの要素にマウスカーソルが掛かったら(要素にホバーしたら)処理を行うには

$(".foo").on("hover",function(){...});

ではなく、mouseenterを使って

$(".foo").on("mouseenter",function(){...});

と書くのが正解です。(マウスカーソルが外れた場合の処理は今回省略)


なので.fooの要素をクリックしても、マウスカーソルが掛かっても(ホバーしても)処理を行いたい場合は以下の様に書けば良いということです。

$(".foo").on("click mouseenter",function(){...});



jQueryをしっかり学ばれている方なら「何言ってんの?」というレベルの話かもしれませんが、ちょっとハマったので忘れないようにブログ記事にしておきました。


それでは、よいjQueryライフを。



●参考

カテゴリー:

このページをぜひシェアしてください