Search code examples
javascriptjqueryjquery-eventsdom-manipulation

How to make a hover listener optional


I've been having some difficulties, could someone point me in the right direction for this fiddle?

I need the div to animate on hover, but only when the .isDown class has been added to a different element by the click function.

Fiddle

$(".move").click( function(event){
event.preventDefault();
if ($(this).hasClass("isDown") ) {
    $(this).stop().animate({opacity:"0.5"}, 270);
    $(this).removeClass("isDown");
            
            //can put hover in here????
} else {
    $(this).stop().animate({opacity:"1"}, 300);
    $(this).addClass("isDown");
}
return false;
});

if ($(".move").hasClass("isDown")){

$(".funnyMOVE").hover(
   function() {
       $(this).stop().animate({top:"10px"},215);
   }, 
   function() {
       $(this).stop().animate({top:"0px"},230);
});

}

Solution

  • Here is working code:

    I removed your code outside of the .move click and put this in it:

    $(".fuckerMOVE").hover(function () {
        $(this).stop().animate({
            top: "10px"
        }, 215);
    },
    function () {
        $(this).stop().animate({
            top: "0px"
        }, 230);
    });
    

    Fiddle

    The problem was that if ($(".move").hasClass("isDown")){ was reached on document load, where this would have been false. My solution was just to apply the hover bind on the element directly when you are wanting it to be bound.


    I actually just realized it looks like you were wanting to remove the bind if the .move is clicked again. If this is the case, you can move your bind into your else block and then add this to the if block:

    $(".fuckerMOVE").off("mouseenter mouseleave");
    

    The reason for mouseenter and mouseleave is that behind the scenes hover() sets listeners for these events.

    Fiddle