-1

I am trying to play with jQuery mouseenter and mouseleave events but failing.

Here is what I am trying to do

$("#selector").mouseenter(function(){
        some code....
        jQuery(this).off('mouseenter'); 
    }
);
$("#selector").mouseleave(function(){
    some code....
    jQuery(this).on('mouseenter');
});

In this .off() is working but unfortunately .on is not working.

Can anyone help me here?

Thx in advance.

>

Edit: Sorry for less information in my above question.

I need to open tooltip on mouseenter and have some buttons in that tooltip. This tooltip is appended in same div. So when I try to click on button in the tooltip it calls mouseenter event and so tooltip is appended again in the div. So I am calling .off() event once tooptip is called till mouse doesn't leave selector.

Let me know if you need more information.

Thx again.

Marc
  • 16,170
  • 20
  • 76
  • 119
Shashi
  • 71
  • 2
  • 10

3 Answers3

1

You need to rebind the event to a handler. $(this).on('mouseenter'); will not bind any handler to it.

Try using a function to bind as handler so it can be bounded again and instead of on and off use .one

$("#selector").one('mouseenter', selMouseEnter);

$("#selector").mouseleave(function(){
    some code....
    $("#selector").one('mouseenter', selMouseEnter);
});

function selMouseEnter () {
    some code....
}

Edit: what you are trying to do can be achieved using .hover or simply implementing .mouseenter and .mouseleave functions. No need to bind/unbind as these function called once on mouseenter and mouseleave.

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
0

The on and off methods are not used to turn events on and off, they are used to bind and unbind events.

So, this:

$("#selector").mouseenter(function(){
  some code....
});

does the same as:

$("#selector").on("mouseenter", function(){
  some code....
});

and:

$("#selector").bind("mouseenter", function(){
  some code....
});

You don't have to unbind the event while the mouse is over the element, just handle the mouseenter and mouseleave events:

$("#selector").mouseenter(function(){
  some code....
}).mouseleave(function(){
  some code....
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

What you are trying to do can simply be achieved with:

$("#selector").mouseenter(function(){
    some code....
}).mouseleave(function(){
    some code....
});

There is no rebinding and unbinding required.

Also, you are using .on wrong, you need to pass a function as well. See .on docs .

Esailija
  • 138,174
  • 23
  • 272
  • 326