Reputation: 155
I have a site with three tabs that I'm trying to dynamically add mouseover/mouseout event depending on which tab is clicked, the problem is that it appears that the mouseover/out events are 'bound' to the tab after they're called. Is there a way to 'unbind' the event from the tabs?
Here's what my js looks like
onTab1Clicked()
{
$('#tab2').mouseover(function() {
$('#tab2').addClass('outlineBorder');
});
$('#tab2').mouseout(function() {
$('#tab2').removeClass('outlineBorder');
});
$('#tab3').mouseover(function() {
$('#tab3').addClass('outlineBorder');
});
$('#tab3').mouseout(function() {
$('#tab3').removeClass('outlineBorder');
});
}
onTab2Clicked()
{
$('#tab1').mouseover(function() {
$('#tab1').addClass('outlineBorder');
});
$('#tab1').mouseout(function() {
$('#tab1').removeClass('outlineBorder');
});
$('#tab3').mouseover(function() {
$('#tab3').addClass('outlineBorder');
});
$('#tab3').mouseout(function() {
$('#tab3').removeClass('outlineBorder');
});
}
onTab3Clicked()
{
$('#tab2').mouseover(function() {
$('#tab2').addClass('outlineBorder');
});
$('#tab2').mouseout(function() {
$('#tab2').removeClass('outlineBorder');
});
$('#tab1').mouseover(function() {
$('#tab1').addClass('outlineBorder');
});
$('#tab1').mouseout(function() {
$('#tab1').removeClass('outlineBorder');
});
}
This works fine on page load but if I click away from tab1 (page load state) to another tab then back to tab1 the mouseover/out events still fire.
Thanks.
Upvotes: 2
Views: 9028
Reputation: 630597
You can simplify your approach overall by making some very simple changes here. First, give those #tab1
, #tab2
and #tab3
elements a class, e.g. class="tab"
then you can do this:
$(".tab").click(function() {
$(this).addClass('active'); //make this tab active
$(".tab").not(this).removeClass('active'); //make other tabs inactive
});
Now when you click any tab, it gets the "active" class, and the others won't have it. Then you can use .live()
with the :not()
selector to get the hover effect you want, like this:
$('.tab:not(.active)').live('mouseover mouseout', function() {
$(this).toggleClass('outlineBorder');
});
This selector won't act upon a tab while it's .active
, so the hover effect only works on the tab that isn't selected, like you originally had, but much easier to maintain.
Upvotes: 4
Reputation: 65274
$('#tab1,#tab2,#tab3').click(function(){
$(this).unbind('mouseout mouseover');
// this will unbind mouseout and mouseover events when click
// e.g. onTab1Clicked, mouseout and mouseover events will be unbind on tab1
})
Upvotes: 1