Move between page tabs when pressing the Back and Forward buttons

I have a simple jQuery tab working fine. Code for this function:

$(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:

<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, eg.

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

      

The contents of the tab are not displayed. How can I make the contents of the tab also appear when I press the Back or Forward buttons?

+3


source to share


2 answers


Listen for an event "hashchange"

on the window object and trigger a click on the appropriate anchor on startup.

You can set up the correct link using the jQuery attribute selector. It looks something like this: a[href='#tab1']

. You can get the href link from the url using the property window.location.hash

.



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

      

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

.

+4


source


Use id

insteadhref

 <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 the JSFiddle url from being changed

0


source







All Articles