开发者

How can I create an active tab effect in Jquery depending on the page I'm on?

开发者 https://www.devze.com 2023-03-21 07:38 出处:网络
There are many tutorials that show you how to create an active tab effect in a navigation bar by fetching the # from the url.

There are many tutorials that show you how to create an active tab effect in a navigation bar by fetching the # from the url.

This is great if you are linking to the same page, but what if all your links are on different pages. Is there a way using Jquery to fetch the url and make the tab active?

The following example gives the specific tab a class "active":

var tabs = $('ul.tabs');

    tabs.each(function(i) {
        //Get all tabs
        var tab = $(this).find('> li > a');
        tab.click(function(e) {

            //Get Location of tab's content
            var contentLocation = $(this).attr('href') + "Tab";

            //Let go if not a hashed one
            if(contentLocation.charAt(0)=="#") {

                e.preventDefault();

                //Make Tab Active
                tab.removeClass('active');
                $(this).addClass('active');

                //Show Tab Content & add active class
                $(contentLocation).show().addClass('active').siblings().hide().removeClass('active');

            } 
        });

How do I modify this to work with links to other pages within my site? Here is the html:

<ul id="nav"  class="tabs">
    <li><a href="/" title="Home" class="active">Home</a></li>   
    <li><a href="/about/" title="About us">About</a></li>
    <li><a href="/demo/" title="Demo">Demo</a></li>
    <li><a href="/where/" class="dir" title="Where">Where</a></li>
    <li><a href="/contact/" class="dir" title="Contact Us">Contact Us</a></li>
</ul>

The above jquery only works for #tab1, #tab2 etc, how do I make the tab active depending on 开发者_StackOverflow中文版the current page name? Sorry if this is a little unclear, it's quite hard to explain!


On the load of the page you can check the 'window.location' object for what page is being displayed, and then set the 'active' class to the corresponding link:

$(document).ready(function () {
    //iterate through your links and see if they are found in the window.location.pathname string
    var loc_href = window.location.pathname;
    $('#nav a').each(function () {
        if (loc_href == $(this).attr('href')) {
            $(this).addClass('active');
        }
    });
});

NOTE: that the loc == $(this).attr('href') line looks to see if the href values for the links exactly match the window.location.pathname string.


location.href

Will return the URL of the current page, so you could change your if statment to something like -

if (location.href.indexOf(contentLocation) != -1) {

Which will check to see if the link of the clicked href is contained in the current page's URL. You'd obviously have to change this logic to suit your own needs.

0

精彩评论

暂无评论...
验证码 换一张
取 消