Addy Addy -3 years ago 76
jQuery Question

How to remove active class from default tab to another tab based on the URL?

I want a John's tab to be active using the class "active" when the page loads. However, if the URL ends with a specific hashtag (in this case #cindy), I want Cindy's tab to activate when the page loads instead (example: 'www.index.html#cindy').

I've gotten the page to activate John's tab so far, but I don't know where to go from here to make go to Cindy's tab based off the URL.

Any help would be appreciated.

CSS

#main-container .onPage.active {
display: block;
}
#main-container .onPage {
display: none;
}


HTML

<div id="main-container">
<div class="box">
<div class="btnList" id="tabs">
<ul>
<li>
<a class="tab linkSection" href="#james"><span>James</span></a>
</li>
<li>
<a class="tab linkSection" href="#cindy"><span>Cindy</span></a>
</li>
</ul>
</div>
<div class="onPage" id="james">
<div>
<h1 class="icon"><span class="b"></span>Meet James</h1><br>
</div>
</div>
<div class="onPage" id="cindy">
<div>
<h1 class="icon"><span class="b"></span>Meet Cindy</h1><br>
</div>
</div>
</div>
</div>


JS

$(document).ready(function() {
$("div#james.onPage").addClass("active");
});

Answer Source

Get hash from url and check if it is blank or not and take decision from that which one to activate.

$(document).ready(function() {
    var hash = window.location.hash;
    if(hash) {
        $("div" + hash + ".onPage").addClass("active");
    } else {
        $("div#james.onPage").addClass("active");
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download