Vineet
Vineet

Reputation: 387

Navigate between page tabs when the browser's Back and Forward buttons are clicked

I have a simple jQuery tab working fine. The code for this feature is:

$(document).ready(function() {
    var tabHead = $('ul li');
    var tabContent = $('.content');

    tabContent.not(':first').hide().end();
    tabHead.on('click',function() { 
        tabContent.hide().eq($(this).index()).show();
    });
});

And the HTML markup for the tabs is:

<ul>
    <li><a href="#content1">Head 1</a></li>
    <li><a href="#content2">Head 2</a></li>
</ul>

<div class="content"> Some Content/........</div>
<div class="content"> Some Content/........</div> 

However, when I click the "Back" and "Forward" buttons of the browser, only the url changes e.g.

http://some-path/demo-tabs/#tab2

The content of the tab does not show up. How can I make the tab's content also show up on clicking the "Back" or "Forward" buttons?

Upvotes: 3

Views: 1534

Answers (2)

nbrooks
nbrooks

Reputation: 18233

Listen for the "hashchange" event on the window object, and trigger a click on the relevant anchor link when that's fired.

You can target the correct link using the jQuery attribute-equals selector. That looks something like this: a[href='#tab1']. You can get the link's href from the URL via the window.location.hash property.

$(window).on("hashchange", function() {
    $("a[href='" + window.location.hash + "']").click();
});

Take a look at this list of browsers that support the hashchange event.

Upvotes: 4

Captain Planet
Captain Planet

Reputation: 408

Use id instead of href

 <ul>    
        <li><a id="#content1">Head 1</a></li>
        <li><a id="#content2">Head 2</a></li>
    </ul>

    <div class="content"> Some Content/........</div>
    <div class="content"> Some Content3........</div> 

This will prevent change in URL JSFiddle

Upvotes: 0

Related Questions