I\'m new to jQuery, so I\'m sorry if this is a silly question. But I\'ve been looking through Stack Overflow and I can find things that half work, I just can\'t get it to f
Try this one:
$(document).ready(function() {
$(".tab").click(function () {
$("this").addClass("active").siblings().removeClass("active");
});
});
$(document).ready(function() {
$(".tab").click(function () {
if(!$(this).hasClass('active'))
{
$(".tab.active").removeClass("active");
$(this).addClass("active");
}
});
});
Try this
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
// $(".tab").addClass("active"); // instead of this do the below
$(this).addClass("active");
});
});
when you are using $(".tab").addClass("active");
, it targets all the elements with class name .tab
. Instead when you use this
it looks for the element which has an event, in your case the element which is clicked.
Hope this helps you.
You can remove class active
from all .tab
and use $(this)
to target current clicked .tab
:
$(document).ready(function() {
$(".tab").click(function () {
$(".tab").removeClass("active");
$(this).addClass("active");
});
});
Your code won't work because after removing class active
from all .tab
, you also add class active
to all .tab
again. So you need to use $(this)
instead of $('.tab')
to add the class active
only to the clicked .tab
anchor
Updated Fiddle
Use jquery cookie https://github.com/carhartl/jquery-cookie and then you can be sure the class will stay on page refresh.
Stores the id of the clicked element in the cookie and then uses that to add the class on refresh.
//Get cookie value and set active
var tab = $.cookie('active');
$('#' + tab).addClass('active');
//Set cookie active tab value on click
//Done this way to preserve after page refresh
$('.topTab').click(function (event) {
var clickedTab = event.target.id;
$.removeCookie('active', { path: '/' });
$( '.active' ).removeClass( 'active' );
$.cookie('active', clickedTab, { path: '/' });
});
You alread removed the active class from all the tabs but then you add the active class, again, to all the tabs. You should only add the active class to the currently selected tab like so http://jsfiddle.net/QFnRa/
$(".tab").removeClass("active");
$(this).addClass("active");