Robert Hanson Robert Hanson - 7 months ago 17
Javascript Question

jQuery .hasClass() failed for tab changes

I have this HTML structure :

<div class="tab-pane slide-left padding-20" id="tab1">...</div>
<div class="tab-pane slide-left padding-20 active" id="tab2">...</div>
<div class="tab-pane slide-left padding-20" id="tab3">...</div>


current active tab will have
active
class, that's why, I want to create conditional function to handle some variables when
tab2
is active using this code :

<script>
$(document).ready(function(){
if ($("#tab2").hasClass("active")) {
alert ("yes it's active!!");
}
});
</script>


but it's not working. no alert message shows up when
#tab2
is active. how to make this works? thank you.

Please note : tab changes doesn't reload all the page.

GG. GG.
Answer

You can do something like that.

$('.tab-pane').on('click', function () {
    if ($(this).hasClass("active")) {
        alert($(this).attr('id') + " it's active!!");
    }
});

DEMO

Or directly:

$('.tab-pane.active').on('click', function () {
    alert($(this).attr('id') + " it's active!!");
});

DEMO