1

I'm trying to capture the event when the mouse is hovering over the select box, be it collapsed or expanded. I'm using .on() in the following manner,

$(document).on('hover', "select#selectBox", function() {
    alert("done");
  });

Please note that I'm using this snippet inside DOM document ready too.

I've tried changing the event to click, scroll, mouseover, mouseenter, etc too. Doesn't seem to work for those too.

Please point out where I'm going wrong.

I've made a JSFiddle: https://jsfiddle.net/g9vf1mty/2/

EDIT: Thanks for the quick response everyone! I have fixed my mistakes :)

I have tweaked the JSFiddle a little bit. Now, I'm attempting to scroll the select box with a size lesser than the number of options and have changed the 'hover' event to 'scroll' event. It does not seem to work that way.

I'm using jQuery 2.1.3.

JSFiddle here: https://jsfiddle.net/g9vf1mty/8/

Ozil
  • 945
  • 3
  • 11
  • 28

3 Answers3

4

You don't need to wrap event bound to document level inside ready pseudo event. And because you want to delegate event, maybe to hanlde dynamic elements, the correct way would be to bind both mouseenter & mouseleave events this way:

eventually filtering by event type inside handler (in/out)

$(document).on('mouseenter mouseleave', "#selectBox", function(e) {
  alert("done: " + e.type);
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • 1
    Scroll event doesnt bubble which is required for delegating it. See workaround http://stackoverflow.com/a/30476388/1414562 – A. Wolff Apr 19 '16 at 18:55
  • Thanks for the important information that Scroll event doesn't bubble. – Ozil Apr 19 '16 at 20:37
3
$("select#selectBox").hover(function() {
 alert("working");
});

use hover function, in the above manner. and more importantly, you missed jQuery library too.

As on("hover") was deprecated form jQuery 1.8, it won't work on Higher versions of jquery.

ameenulla0007
  • 2,663
  • 1
  • 12
  • 15
  • It's not 100% correct, as the `hover()` event works in v1.8.3, it was deprecated from v1.9 or higher. You can check it in the official documentation: https://jquery.com/upgrade-guide/1.9/ – fbid Apr 19 '16 at 15:21
  • @fbid, read the authentic source here http://api.jquery.com/on/#additional-notes, which says _Deprecated in jQuery 1.8, removed in 1.9_, i used the word deprecated.. :) – ameenulla0007 Apr 19 '16 at 15:27
  • But you aren't delegating events here – A. Wolff Apr 19 '16 at 15:30
  • yes, it was deprecated from v.1.8 but you wrote that it won't work on higher version than 1.8, that was not 100% correct, anyway it was just to clarify – fbid Apr 19 '16 at 15:33
  • yup.. Thanks for the info then. :) – ameenulla0007 Apr 19 '16 at 15:34
1

You should use mouseenter event

and include jquery in your fiddle :)

Look also at this (SO question)[Is it possible to use jQuery .on and hover?

Community
  • 1
  • 1
Pietro
  • 988
  • 10
  • 19