I’ve got two jQuery functions that serve different functionality to the same elements.
Here is my basic HTML markup:
<ul>
<li class="active">
<a href="#head1" data-toggle="tab" class="fade">
<img src="head1_down.jpg" />
</a>
</li>
<li>
<a href="#head2" data-toggle="tab" class="fade">
<img src="head2_down.jpg" />
</a>
</li>
<li>
<a href="#head3" data-toggle="tab">
<img src="head2_down.jpg" />
<!-- Does not fade! No .fade class on link tag. -->
</a>
</li>
</ul>
The first function lookFade() adds a fade-effect that changes the source of the images on mousehover:
// Helper functions
$.fn.lookUp = function() {
$(this).attr('src', function(i,val) { return val.replace('down.jpg', 'up.jpg') });
return $(this);
}
$.fn.lookDown = function() {
$(this).attr('src', function(i,val) { return val.replace('up.jpg', 'down.jpg') });
return $(this);
}
$.fn.lookFade = function() {
$(this).hover(
function() {
$(this).fadeOut(function() {
$(this).lookUp().fadeIn();
})
},
function() {
$(this).fadeOut(function() {
$(this).lookDown().fadeIn();
})
}
);
return $(this);
}
// Change .active image on pageload
$('li.active > a.fade > img').lookUp();
// Fade effect on hover
$('li:not(.active) > a.fade > img').lookFade();
The second function toggles the content panes (not shown in markup, this works!) when the link item is clicked. It also changes the image inside the link tag and changes the .active class from the current li element to the clicked li element.
// Toggle tabs and change .active
$('a[data-toggle="tab"]').click(function() {
var head = $(this).attr('href');
var active = "#" + $('.pane.active').attr('id');
if (head != active) {
$(active).removeClass('active');
$(head).addClass('active');
$(this).children('img').lookUp();
$(this).parent().parent().children('li.active').removeClass('active');
$(this).parent().addClass('active');
}
});
Problem: When clicking a link it works the content panes change and even the classes get adjusted correctly. But the lookFade() function doesn’t recognize the class changes and still fades for the now .active li elements (and doesn’t for those who lost this class by clicking).
Changing the class of an element does not change the events bound to it. Events are bound to the element, not the class. If you want that type of functionality, use event delegation with .on() or .delegate()
Since you are using plugins to perform these actions, it won’t be as easy to make it work. I would ditch the
lookFademethod and bind thelookFadeevents (mouseenterandmouseleave) using event delegation.Quick example: