Remember which tab was active after refresh

JqueryJquery Plugins

Jquery Problem Overview


I'm using jquery tabs on a web page and when the page is refreshed it loses what ever tab I had been on and goes back to the first tab.

Has anyone come across this problem and know how to solve it?

Jquery Solutions


Solution 1 - Jquery

Like others I was struggling with my ui-tabs cookie history in jQueryUI 1.10. Thanks to Harry's solution and some other online documentation I refer to in the code below I now have a working non-cookie solution! I was able to test in Firefox 18.0.1 and IE 9.0.12. According to my resources, Chrome, Firefox, Safari and IE8 & above support Session Storage.

  $(function() {
	//	jQueryUI 1.10 and HTML5 ready
	//		http://jqueryui.com/upgrade-guide/1.10/#removed-cookie-option 
	//	Documentation
	//		http://api.jqueryui.com/tabs/#option-active
	//		http://api.jqueryui.com/tabs/#event-activate
	//		http://balaarjunan.wordpress.com/2010/11/10/html5-session-storage-key-things-to-consider/
	//
	//	Define friendly index name
	var index = 'key';
	//	Define friendly data store name
	var dataStore = window.sessionStorage;
	//	Start magic!
	try {
		// getter: Fetch previous value
		var oldIndex = dataStore.getItem(index);
	} catch(e) {
		// getter: Always default to first tab in error state
		var oldIndex = 0;
	}
	$('#tabs').tabs({
		// The zero-based index of the panel that is active (open)
		active : oldIndex,
		// Triggered after a tab has been activated
		activate : function( event, ui ){
			//	Get future value
			var newIndex = ui.newTab.parent().children().index(ui.newTab);
			//	Set future value
			dataStore.setItem( index, newIndex ) 
		}
	}); 
    });	
  

Solution 2 - Jquery

I assume that you are using jQuery UI tabs ,

here is an example of using tabs + cookies to save the last clicked tab

http://jqueryui.com/demos/tabs/#cookie

demo : open this link http://jqueryui.com/demos/tabs/cookie.html

the close it and re open it and you will see the same clicked tab

update: after 3 years of this answer jquery ui has deprecated the cookie option : http://jqueryui.com/upgrade-guide/1.9/#deprecated-cookie-option.

but you can still append take a look here if this fits your needs or not https://stackoverflow.com/a/14313315/109217

Solution 3 - Jquery

A simpler alternative I have just implemented:

$(".tabs").tabs({
    select: function(event, ui) {	                
       window.location.replace(ui.tab.hash);
    },
});

That will add the hash value to the url so a page refresh will reload that tab, and by using location.replace rather than location.hash, we don't fill the user's history up with unwanted steps back.

Hope that helps.

Solution 4 - Jquery

Now that cookie is gone in jQuery UI 1.10.0, I mixed Gayathiri's approach with the new options and events:

// using cookie plugin from https://github.com/carhartl/jquery-cookie

var tabCookieName = "ui-tabs-1";
$(".tabs").tabs({
    active : ($.cookie(tabCookieName) || 0);
    activate : function( event, ui ) {
        var newIndex = ui.newTab.parent().children().index(ui.newTab);
        // my setup requires the custom path, yours may not
        $.cookie(tabCookieName, newIndex, { path: window.location.pathname });
    }
});

Solution 5 - Jquery

Short, layout-independent way of doing this using localStorage:

$("#tabs").tabs({
  active: localStorage.getItem("currentIdx"),
  activate: function(event, ui) {
      localStorage.setItem("currentIdx", $(this).tabs('option', 'active'));
  }
});

A layout-specific way of doing it using custom data attributes (possibly useful if the attribute values were to be used in some way elsewhere in your script).

jQuery UI:

$("#tabs").tabs({
    active: localStorage.getItem("currentTabIndex"),
    activate: function(event, ui) {
        localStorage.setItem("currentTabIndex", ui.newPanel[0].dataset["tabIndex"]);
    }
});

Example HTML layout:

<div id="tabs">
    <div id="tabs-1" data-tab-index="0">
       tab 1 stuff...
    </div>
    <div id="tabs-2" data-tab-index="1">
       tab 2 stuff...
    </div>    
    <div id="tabs-3" data-tab-index="2">
       tab 3 stuff...
    </div>
</div>

Solution 6 - Jquery

If you're using bootstrap 3 or 4 tabs, you could use local storage to store the current tab id then set it to show on page load. First you'll prevent the default method to open the tab, then save the opened tab link id on tab open event.

 $('a[data-toggle="tab"]').click(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });

    $('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
        var id = $(e.target).attr("href");
        localStorage.setItem('selectedTab', id)
    });

    var selectedTab = localStorage.getItem('selectedTab');

    if (selectedTab != null) {
        $('a[data-toggle="tab"][href="' + selectedTab + '"]').tab('show');
    }

Always works fine for me.

Solution 7 - Jquery

When web pages refresh, they reload their state from the server, by requesting the page again.

Either the webserver needs to remember the state and supply the file differently than the default, or you may be able to use cookies or the hash-component of the URL and some jQuery to store the state, read it on load and restore it.

See the jquery.cookie plugin or SWFaddress, learn about manipulating hash values yourself or the jQuery History plugin.

The hash method has a particular attraction as it replicates changes of URL, so copy/paste of the URL still works, as do bookmarks.

Solution 8 - Jquery

Include the jquery cookies plugin :

<script type="text/javascript" src="/resources/js/jquery.cookies.2.2.0.min.js"></script>

declare a cookie name inside $.function({.. or document.ready as

var cookieName = "mycookie";

$("#tabs").tabs({
	selected : ($.cookies.get(cookieName) || 0),
	select : function(e, ui) {
		$.cookies.set(cookieName, ui.index);
	}
        });

Solution 9 - Jquery

You can try something like this, it's pretty easy to do.

# Set selected_tab to the correct index based on the current url anchor hash
selected_tab = 0
if matches = /#(\w+)/.exec(window.location.hash)
  # find the index of the tab with the given id
  selected_tab = $('#' + matches[1]).index() - 1

# Initialize the tabs and set 'selected' to equal the selected_tab variable we just set
$('.tabable').tabs
  selected: selected_tab,  # this is where the magic happens
  select: (evt, ui) ->
    window.location.hash = ui.panel.id  # set an anchor tag in the url with the tab id

Solution 10 - Jquery

Another option is to use html 5 storage. See here for an example: http://www.w3schools.com/html/html5_webstorage.asp

Solution 11 - Jquery

Here is an alternative way to allow remembering the open tab by the element id (not index). This is useful, if you use this code to synchronize the open tabs on two different pages with similar elements (like show and edit page).

var tabsid = "#tabs";
var cookieid = "tabs_selected2";

var activetabnr = 0;
if (($.cookie(cookieid)!=null) && ($.cookie(cookieid)!="")) {
   activetabnr = $(tabsid+' a[href="'+$.cookie(cookieid)+'"]').parent().index();
}

$(tabsid).tabs({
   active: $(tabsid).tabs({ active: activetabnr }),
   beforeActivate: function (event, ui) {
        $.cookie(cookieid, "#"+ui.newPanel.attr('id'));
   }
});

Works with jQuery UI 1.10. Do not forget to include the jquery.cookie plugin!

<script type="text/javascript" src="/js/jquery.cookie.js"></script>

Solution 12 - Jquery

You can use the jQuery History plugin, here is a demo (load another link in the demo and try refreshing)

Solution 13 - Jquery

My company blocks cookies so I found a workaround. Simply keep track of the tab using a hidden field and pass that value back once the request is finished. It's not pretty but it gets the job done.

<% if(request.getAttribute("tab")==null) { %>
	$("#tabs").tabs();
<% } else { %>
	$("#tabs").tabs({selected:<%=request.getAttribute("tab").toString() %>});
<% } %>

On the back end I just set the attribute

request.setAttribute("tab", f.get("tab").toString());

Hope this helps.

Solution 14 - Jquery

Do you think you can add same function on below code.

$(".menu > li").click(function(e){
    $(".content." + $(".menu > .active").attr("id")).fadeOut("fast", function() {
        $(".content." + e.target.id).fadeIn();
        $(".menu > #" + e.target.id).addClass("active");
    });

    $(".menu > .active").removeClass("active");
					
    return true;
			
});

Solution 15 - Jquery

   $(function () {
        
        $("#dialog").dialog({
            autoOpen: false,
            show: {
                effect: "blind",
                duration: 1000
            },
            hide: {
                effect: "explode",
                duration: 1000
            }
        });

        //$(function () {
            $("#tabs").tabs({
                    select: function (event, ui) {                       
                    document.location.href = ui.tab.href;                        
                }
            }).show();

        //});

                    $("#MainContent_button1").click(function (event) {                           
                        event .preventDefault();
                         $("#dialog").dialog("open");                           
                    });
    });

I used it in ASP.NET and it works fine for me. I am also having a button in second tab to show some dialog box and it works perfect.

Pooja Dhingra

Solution 16 - Jquery

I am resolved the same issue with the help of following blog.

> HTML Tab

 <ul class="tabs clear-fix">
     <li class=""><a href="#tab=java" id="tab1-tab"><i class=" fa fa-search-plus fa-lg" style="font-size:16px; "></i>JAVA</a><span></span></li>
     <li class=""><a href="#tab=js"  id="tab2-tab"><i class=" fa fa-user fa-lg" style="font-size:16px;"></i>JAVA SCRIPT</a><span></span></li>
     <li><a href="#tab=c"  id="tab3-tab"><i class="fa fa-archive fa-lg" style="font-size:16px;"></i>C</a><span></span></li>
     <li><a href="#tab=c2"  id="tab4-tab"><i class=" fa fa-gift fa-lg" style="font-size:16px;"></i>C++</a><span></span></li>
     <li><a href="#tab=jQ"  id="tab5-tab"><i class=" fa fa-heart fa-lg" style="font-size:16px;"></i>jQuery</a><span></span></li>
    </ul>

> Javascript

 var selectedTab =  window.location.href.split("#tab=")[1] ;
	var selectedId = $('a[href$=' + selectedTab+']:first').attr('id');
	
	if (typeof selectedId === "undefined") {
		 $('#tab1-tab').trigger("click");
	}
	else{
		$('#'+selectedId).trigger("click");
	}

For me it worked, suggestion appreciated.

Solution 17 - Jquery

I've recently had the same problem and spent a longtime looking at the docs for JQuery UI Tabs Widget. I ended up using the events activate and create for JQuery UI 1.10 as well as localStorage to store the current tab before page refresh.

    $( ".selector" ).tabs({                                                 
		activate: function( event, ui) {
			//when tab is activated store it's index in activeTabIndex
           		var activeTabIndex = $('.tabs').tabs('option','active');
			//add activeTabIndex to localStorage and set with key of 'currentTab'  
          		localStorage.setItem('currentTab', activeTabIndex); 
                			},
            create: function( event, ui ) {
             	$(".tabs").tabs({		
			//when tabs are created on page refresh, the active tab is set to index of 'currentTab' 
			//after getItem from localStorage
			active: localStorage.getItem('currentTab')
		});
      }
   });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthegunnerView Question on Stackoverflow
Solution 1 - JqueryArikView Answer on Stackoverflow
Solution 2 - JquerytawfekovView Answer on Stackoverflow
Solution 3 - JqueryHatchamView Answer on Stackoverflow
Solution 4 - JqueryHarryView Answer on Stackoverflow
Solution 5 - JquerydsgriffinView Answer on Stackoverflow
Solution 6 - JqueryManuEl MagakView Answer on Stackoverflow
Solution 7 - JqueryOrblingView Answer on Stackoverflow
Solution 8 - JqueryPoppyView Answer on Stackoverflow
Solution 9 - JqueryRyanView Answer on Stackoverflow
Solution 10 - JqueryMaurizio In denmarkView Answer on Stackoverflow
Solution 11 - JqueryJeffView Answer on Stackoverflow
Solution 12 - JqueryJosh StodolaView Answer on Stackoverflow
Solution 13 - JquerybmoranView Answer on Stackoverflow
Solution 14 - JquerySahbas HasView Answer on Stackoverflow
Solution 15 - JqueryPooja DhingraView Answer on Stackoverflow
Solution 16 - Jquerylight_rayView Answer on Stackoverflow
Solution 17 - Jqueryincreda_jawView Answer on Stackoverflow