简体   繁体   中英

Setting active tab based on url

I have a simple tabbed interface that switches between hidden div and sets an active state on the appropriate tab when clicked.

When someone visits the url of the tab, it shows the contents of that tab only, which is fine.

What I need it to do is also set the active state of that tab if you visited that url directly.

I've got url's such as abc.com/index.html#gallery, abc.com/index.html#recipes etc.

So if you visit abc.com/index.html#recipes - the recipes tab is highlighted.

My code is below, thanks in advance for any advice!

    $(function () {
var app = {
        vars: {
            gallery: $('#gallery'),
            tabContent: $('.tabs .tabContent'),
            nav: $('.tabs nav a')
        },
        events: function () {
            //tabs
            app.vars.nav.on('click', function (e) {
                var thisHash = $(this).attr('href');
                app.setHash(thisHash);
                e.preventDefault();
                $('nav a').removeClass('active');
                $(this).addClass('active');
            });

            //hashchange
            $(window).on('hashchange', function() {
                app.checkHash();
            });

        },
        checkHash: function () {
            var hash = app.getHash();

            if (hash == '') {
                app.vars.tabContent.hide();
                app.vars.gallery.show();
            } else {
                app.goTo(hash);
            }

        },
        getHash: function () {
            return window.location.hash;
        },
        setHash: function (id) {
            window.location.hash = id;
        },
        goTo: function (id) {
            app.vars.tabContent.hide();
            $(id).fadeIn();
        }
    }
app.events();
app.checkHash();


});

You need to amend the goTo function to set the active class on the relevant tab. Try this:

goTo: function (id) {
    app.vars.tabContent.hide();
    $(id).fadeIn();
    $('nav a[href="' + id + '"]').addClass('active').siblings().removeClass('active');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM