Sorin David
Sorin David

Reputation: 19

How do I keep the current tab active after a page reload?

I'm currently using tabs and want to select the same tab after a user has posted data and the page reloads.

Javascript:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var $items = $('#vtab>ul>li');
        $items.mousedown(function() {
            $items.removeClass('selected');
            $(this).addClass('selected');

            var index = $items.index($(this));
            $('#vtab>div').hide().eq(index).show();
        }).eq(0).mousedown();
    });
</script>

Tabs:

<div id="vtab">
    <ul>
        <li class="user"><a href="#">User</a></li>
        <li class="category"><a href="#">Category</a></li>
    </ul>
<!--user-->        
    <div>Content</div>
</div>
<!--category-->        
    <div>Content</div>
</div>

Thank you!

Upvotes: 0

Views: 938

Answers (1)

Cymen
Cymen

Reputation: 14429

One easy way is to post the data via XMLHttpRequest aka AJAX. That way, your whole page won't redirect. The other solution is to put the active tab in the URL. That has the side benefit of allowing bookmarks to return to the correct tab too. To put the tab in the URL, look at pushstate (and consider a polyfill/backwards compatible approach to work with browsers that do not have pushstate).

Upvotes: 1

Related Questions