Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery if has class issue

I am using bootstrap tabs and I wanted to do some functions with javascript if LI is clicked but with conditional, if it's active do nothing, else do this...

I have come up with this code to check if it has a class="active" since bootstrap tabs adds class="active" to LI for the active tab but it doesn't work well, it always returns true, what I am 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 is jsfiddle demo

like image 560
skyline33 Avatar asked May 13 '26 16:05

skyline33


1 Answers

Use $(this) for taken current object

$( "li" ).click(function() {

    if ($(this).hasClass("active")) {
       console.log("the tab is already active");
    }   
    else {
          console.log("selected");
    }

});

Fiddle

like image 106
Sudharsan S Avatar answered May 15 '26 05:05

Sudharsan S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!