Skip to content Skip to sidebar Skip to footer

How Do I Properly Use The Jquery Off() Method To Remove The Mouseenter And Mouseleave Events Off An Element

I seem to be having some trouble removing some events from an element using the jQuery off() method. I want to remove the mouseenter and mouseleave events when I match a certain cr

Solution 1:

Lets do some DOM manipulations and throw some conditions

//Page loaded - jQuery Ready
$(document).ready(function () {

    //User hovering over article. Change BG.
    $(document).on('mouseenter', '.Article', function () {
        if( !( $(this).hasClass('donotSelect') ) )
            $(this).css('background', '#F0F8FF');
        else
             $(document).off('mouseleave', $(this));
    }).on('mouseleave', '.Article', function () {
        if( !( $(this).hasClass('donotSelect') ) )
            $(this).css('background', '#FFFFFF');
        else
             $(document).off('mouseenter', $(this));
    });

    //Set active BG color if condition is met.
    $('.LatestMediaID').each(function () {
        varLatestMediaID = $(this).val();     

        //Disable mouseenter and mouseleave events on the matched Article.if (LatestMediaID == $('#HiddenMediaID').val()) {
            $(this).parent().addClass("donotSelect");
            //Change BG color to light blue.    
            $(this).parent().css('background', '#F0F8FF');
        }
    });

});

http://jsfiddle.net/GE7Wg/5/

Solution 2:

Not sure what his causing the problem, but you could avoid adding the events in the first place by checking the value up front.

Maybe use something like:

$(function() {
    var hidID = $("#HiddenMediaID").val();
    $(".Article").each(function(){
        var article = $(this);
        if(article.find(".LatestMediaID").val() !== hidID)
        {
            article.on("mouseenter", function(){ article.css("background", "#F0F8FF") });
            article.on("mouseleave", function(){ article.css("background", "#FFFFFF") });
        }
    });
});

Solution 3:

There is a way to do it the way you want by adding another event on the selected article level http://api.jquery.com/event.stopPropagation/ from there, but thas is really ugly. Much cleaner to handle this via CSS http://jsfiddle.net/liho1eye/GE7Wg/4/

.selected, .hover { background-color:#F0F8FF;}​

Script:

$(document).on('mouseenter mouseleave', '.Article', function(e) {
    $(this).toggleClass("hover", e.type == "mouseenter");
});

Post a Comment for "How Do I Properly Use The Jquery Off() Method To Remove The Mouseenter And Mouseleave Events Off An Element"