Nir
Nir

Reputation: 318

jquery: unbind mouseenter and leave won't work

i have a tabbed view and when i hover above unselected tabs i give it the same style as a selected tab. the problem is that when i click it i can't seem to unbind the enter and leave events.

function DocReady() {
    $("." + TAB_OFF_CLASS).click(changeCategory);
    $("." + TAB_OFF_CLASS).mouseenter(onCategoryOver);
    $("." + TAB_OFF_CLASS).mouseleave(onCategoryOut);
}

function onCategoryOver() {
    $(this).removeClass(TAB_OFF_CLASS).addClass(TAB_ON_CLASS);
}
function onCategoryOut() {
    $(this).removeClass(TAB_ON_CLASS).addClass(TAB_OFF_CLASS);
}

function changeCategory() {

var catTab = $(this);
var catName = catTab.find('#catName').html();
var id = catTab.attr('categoryID');
catTab.unbind('click');
catTab.unbind('mouseenter', onCategoryOver);
catTab.unbind('mouseleave', onCategoryOut);
catTab.removeClass(TAB_OFF_CLASS).addClass(TAB_ON_CLASS);    
...

}

as you can u see i also tried to bind it again to an empty function doesn't work either. update: the unbind works only when i click the tab and stay over it until the code finishes. but if i click and pull out it doesn't. i guess it's because the mouseleave event fires in the middle of the click handler. anyone...?

Upvotes: 4

Views: 8048

Answers (3)

kgiannakakis
kgiannakakis

Reputation: 104178

Using the empty functions won't work. With jQuery you can add as many handlers as you want to a specific event. Adding a new one doesn't delete the previous one. The right way to do it is to use the unbind method, the way you are doing it in the code you've commented out.

As I see it, this code should work. I recommend to use Firebug to see if this code is actually called.

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171774

Calling

catTab.mouseenter(function(){});
catTab.mouseleave(function(){});

Will simply add another empty event handler. You should unbind them like this;

catTab.unbind("mouseenter");
catTab.unbind("mouseleave");

Upvotes: 11

RaYell
RaYell

Reputation: 70414

You must add a callback function when you call unbind().

catTab.unBind('click', clickEventHandler);

When you first attach this event handler don't use anonymous function like this:

catTab.click(function () {
   ...
});

// or 

catTab.bind('click', function () {
    ...
});

Instead use the named function

function clickEventHandler() {
    ...
};

catTab.click(clickEventHandler);
// or
catTab.bind('click', clickEventHandler);

Upvotes: -1

Related Questions