Raul Escarcega
Raul Escarcega

Reputation: 1

How to unbind a previous jQuery hover / click event?

I want to unbind the mouseover event when the element is clicked.

HTML markup:

<div id="foto"></div>
<div id="flotante"></div>
<div id="flotante2"></div>    

jQuery code:

$('#foto').on({
    mouseover: function(){
        $('#flotante').delay(2000).show('slow');
    },
    mouseleave: function(){
        $('#flotante').hide('slow');
    },
    click: function(){
        // I want the mouseover event to stop executing.        
         $('#flotante2').show();
    }
});

You can see an example here: http://jsfiddle.net/K85DN/

Thanks a lot for your help

Upvotes: 0

Views: 57

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388326

Some changes

  1. Use namespaced event handlers since we need to remove them.
  2. Use setTimeout() to delay the display since we will have to cancel it if the mouse leaves the element before 2 seconds
  3. Use .stop() to handle the animation queue

Try

var $flotante = $('#flotante');
$('#foto').on({
    'mouseover.display': function () {
        var timer = setTimeout(function () {
            $flotante.stop(true, true).show('slow');
        }, 2000)
        $flotante.data('timer', timer);
    },
    'mouseleave.display': function () {
        clearTimeout($flotante.data('timer'))
        $flotante.stop(true, true).hide('slow');
    },
    click: function () {
        $(this).off('mouseover.display mouseleave.display');
        clearTimeout($flotante.data('timer'));
        $flotante.stop(true, true).hide('slow');
        $('#flotante2').show();
    }
});

Demo: Fiddle

Upvotes: 1

Related Questions