Adding A "current" Class To A Clicked Element And Removing It When Clicking On Another Element?
I am trying to add a class of 'current' to a div with jQuery and then remove the class when a different div is clicked. So far I have the 'current' class being added, but I am not
Solution 1:
Just remove the class on all it's siblings, as being specific avoids confusion when you decide to use .current
somewhere else in the DOM.
$(document).ready(function() {
$('#images div').on('click', function() {
$(this).addClass('current').siblings().removeClass('current');
$('.bios .active').hide().removeClass('active');
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
Solution 2:
$(document).ready(function() {
$('#images div').click(function() {
$('.current').removeClass('current');
$(this).addClass('current');
$('.bios .active').hide().removeClass('active');
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
Solution 3:
You could remove all of the current classes before adding it.
$(document).ready(function() {
$('#images div').click(function() {
$('.current').removeClass('current');
$(this).addClass('current');
$('.bios .active').hide();
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
But the performance will be better if you keep track of the current one and then remove it.
$(document).ready(function() {
var $current;
$('#images div').click(function() {
if($current) $current.removeClass('current');
$current = $(this);
$current.addClass('current');
$('.bios .active').hide();
$('.bios div').eq($(this).index()).show().addClass('active');
});
});
Solution 4:
Just add $('#images div.current').removeClass('current');
before doing $(this).addClass('current');
Post a Comment for "Adding A "current" Class To A Clicked Element And Removing It When Clicking On Another Element?"