Jquery if has class problem
I am using bootstrap tabs and I would like to execute some functionality with javascript if the button is clicked LI
but conditional if it is active does nothing, otherwise do this ...
I came up with this code to check if it isn't has a class="active" since bootstrap tabs adds class="active" to LI for the active tab
, but it doesn't work, it always returns true, what am I doing wrong here?
code
var i = $( "li" ).hasClass( "active" );
$( "li" ).click(function() {
if (i == true ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
here's a jsfiddle demo
Check hasClass for click li:
$( "li" ).click(function() {
if ($(this).hasClass('active') ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Use $(this)
for the current object
$( "li" ).click(function() {
if ($(this).hasClass("active")) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});
Fiddle
Since $ ("li") returns all li tags. And the initial state of the first li tab is active, so the variable i is always true.
Change the codes to what @Bhojendra Sah wrote.
You can also try this for dynamic elements:
$(document).on('click', "li.active", function (e) {
console.log("the tab is already active");
}).on('click', "li:not(.active)", function (e) {
console.log("selected");
});
Example
$( "li" ).click(function() {
if ($(this).hasClass("active") ) {
console.log("the tab is already active");
}
else {
console.log("selected");
}
});