Same tab after page refresh

Hello,
How can I make after page reload/refresh to show last active tab? I used some tutorial for tabs:

<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
    $(document).ready(function() {
        $("#content").find("[id^='tab']").hide();
        $("#tabs li:first").attr("id","current");
        $("#content #tab1").fadeIn();

        $('#tabs a').click(function(e) {
            e.preventDefault();
            if ($(this).closest("li").attr("id") == "current"){
                return;
            }
            else{
                $("#content").find("[id^='tab']").hide();
                $("#tabs li").attr("id","");
                $(this).parent().attr("id","current");
                $('#' + $(this).attr('name')).fadeIn();
            }
        });
    });
</script>

and HTML

<ul id="tabs">
    <li><a href="#" name="tab1">tab1</a></li>
    <li><a href="#" name="tab2">tab2</a></li>
</ul>

<div id="content">
    <div id="tab1">
        <h2>head of tab1</h2><br/>
        // content
    </div>
    <div id="tab2">
        <h2>head of tab2</h2><br/>
        // content 2
    </div>
</div>

You could do it by using some PHP and getting parameters from the URL; but since you are using JavaScript have you considered an AJAX approach? You could then keep a variable that is assigned the active tab, then when you change tabs you can update the variable (and thus update the tab to display).

The PHP solution would probably be best for page reloads; just assign a variable to the url like http://www.mywebsite.com/page.php?tab=tabIDhere and then grab the tab variable assigning it to a javascript var. I hope that makes some sense!

I don’t know how exactly to make it with php and this is working perfectly so far. Just asked if is not so hard to modify this piece of code… I’m totaly new in jquery and kinda begginer in php at all.

I think what Patche means is to use a query string as part of your url.
This is not specific to PHP and will work equally as well with HTML.

For example, set the hrefs of your anchor tags accordingly:

<ul id="tabs">
    <li><a href="?tab=1" name="tab1">tab1</a></li>
    <li><a href="?tab=2" name="tab2">tab2</a></li>
</ul>

Then, when the page loads, you look for the parameter “tab” in the query string and if present open whichever tab it is set to:

function getParameterByName(name) {
    name = name.replace(/[\\[]/, "\\\\[").replace(/[\\]]/, "\\\\]");
    var regex = new RegExp("[\\\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\\+/g, " "));
}

var tab = getParameterByName("tab");
if(tab){
  // open tab here
}

Ref: http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

HTH

Thank’s for you answer. Just one question in line if(tab){ //open tab here } what to put? On my both tabs I have sql querys from msyql…

Maybe trigger a click on them?

var tab = getParameterByName("tab");
if(tab){
  $('[name="' + tab + '"]').trigger("click");
}

Sorry but nothing happen. Doesn’t even change the URL when I try like this

        function getParameterByName(name) {
            name = name.replace(/[\\[]/, "\\\\[").replace(/[\\]]/, "\\\\]");
            var regex = new RegExp("[\\\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\\+/g, " "));
        }
            var tab = getParameterByName("tab");
            if(tab){
                $('[name="' + tab + '"]').trigger("click");
            }

and

 <ul id="tabs">
        <li><a href="?tab=1" name="tab1" >tab1</a></li>
        <li><a href="?tab=2" name="tab2" >tab2</a></li>
    </ul>

Can you post enough code that I can recreate your tabs.
Please only post HTML, JS and CSS (no PHP).

Ok here is the head of page

<head>
    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#content").find("[id^='tab']").hide(); // Hide all content
            $("#tabs li:first").attr("id","current"); // Activate the first tab
            $("#content #tab1").fadeIn(); // Show first tab's content

            $('#tabs a').click(function(e) {
                e.preventDefault();
                if ($(this).closest("li").attr("id") == "current"){ //detection for current tab
                    return;
                }
                else{
                    $("#content").find("[id^='tab']").hide(); // Hide all content
                    $("#tabs li").attr("id",""); //Reset id's
                    $(this).parent().attr("id","current"); // Activate this
                    $('#' + $(this).attr('name')).fadeIn(); // Show content for the current tab
                }

            });

        });
        function getParameterByName(name) {
            name = name.replace(/[\\[]/, "\\\\[").replace(/[\\]]/, "\\\\]");
            var regex = new RegExp("[\\\\?&]" + name + "=([^&#]*)"),
                results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\\+/g, " "));
        }
        var tab = getParameterByName("tab");
        if(tab){
            $('[name="' + tab + '"]').trigger("click");
        }

    </script>
</head>

Here is the body

<ul id="tabs">
        <li><a href="?tab=1" name="tab1" >tab1</a></li>
        <li><a href="?tab=2" name="tab2" >tab2</a></li>
    </ul>

    <div id="content">
        <div id="tab1">
            <h2>Category Bikes</h2><br/>
                  // Here I have query to show category list from mysql
        </div>
        <div id="tab2">
            <h2>Category cars</h2><br/>
                 // Here I have second query to show category list from mysql
        </div>

Here is the CSS of tabs

#tabs {
    overflow: hidden;
    width: 100%;
    margin: 0;
    padding: 0;
    list-style: none;
}

#tabs li {
    float: left;
    margin: 0 .5em 0 0;
}

#tabs a {
    position: relative;
    background: #ddd;
    background-image: linear-gradient(to bottom, #fff, #ddd);
    padding: .7em 3em;
    float: left;
    text-decoration: none;
    color: #444;
    text-shadow: 0 1px 0 rgba(255,255,255,.8);
    border-radius: 5px 0 0 0;
    box-shadow: 0 2px 2px rgba(0,0,0,.4);
}

#tabs a:hover,
#tabs a:hover::after,
#tabs a:focus,
#tabs a:focus::after {
    background: #fff;
}

#tabs a:focus {
    outline: 0;
}

#tabs a::after {
    content:'';
    position:absolute;
    z-index: 1;
    top: 0;
    right: -.5em;
    bottom: 0;
    width: 1em;
    background: #ddd;
    background-image: linear-gradient(to bottom, #fff, #ddd);
    box-shadow: 2px 2px 2px rgba(0,0,0,.4);
    transform: skew(10deg);
    border-radius: 0 5px 0 0;
}

#tabs #current a,
#tabs #current a::after {
    background: #fff;
    z-index: 3;
}

#content {
    background: #fff;
    padding: 2em;
    height: 280px;
    position: relative;
    z-index: 2;
    border-radius: 0 5px 5px 5px;
    box-shadow: 0 -2px 3px -2px rgba(0, 0, 0, .5);
}

Remove this line from your click handler:

e.preventDefault();

Ok, now in URL is changed to ?tab1 or ?tab2 but load only TAB1 … if I click on TAB2 immediately change to tab1 … I can’t even see content of tab2

Ok, let’s do it a bit differently.
The way the thing is coded, we’ll just be fighting it if we use a query string.
Let’s use local storage instead.

Change your JS to this:

$("#content").find("[id^='tab']").hide(); // Hide all content
$("#tabs li:first").attr("id","current"); // Activate the first tab
$("#content #tab1").fadeIn(); // Show first tab's content

$('#tabs a').click(function(e) {
  e.preventDefault();
  if ($(this).closest("li").attr("id") == "current"){ //detection for current tab
    return;
  } else {
    $("#content").find("[id^='tab']").hide(); // Hide all content
    $("#tabs li").attr("id",""); //Reset id's
    $(this).parent().attr("id","current"); // Activate this
    $('#' + $(this).attr('name')).fadeIn(); // Show content for the current tab
  }
  
  var tab = $(this).attr("name");
  localStorage.setItem("tab", tab);
});

var currTab = localStorage.getItem("tab");
$('a[name="' + currTab + '"]').trigger("click");

and place it before the closing body tag:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Accordion</title>
  </head>

  <body>
    <ul id="tabs">
      <li><a href="#" name="tab1" >&#1057;&#1085;&#1080;&#1084;&#1082;&#1080;</a></li>
      <li><a href="#" name="tab2" >&#1042;&#1080;&#1094;&#1086;&#1074;&#1077;</a></li>
    </ul>

    <div id="content">
      <div id="tab1">
        <h2>Category Bikes</h2><br/>
        // Here I have query to show category list from mysql
      </div>
      <div id="tab2">
        <h2>Category cars</h2><br/>
        // Here I have second query to show category list from mysql
      </div>
    </div>

    <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script>
      $("#content").find("[id^='tab']").hide(); // Hide all content
      $("#tabs li:first").attr("id","current"); // Activate the first tab
      $("#content #tab1").fadeIn(); // Show first tab's content

      $('#tabs a').click(function(e) {
        e.preventDefault();
        if ($(this).closest("li").attr("id") == "current"){ //detection for current tab
          return;
        } else {
          $("#content").find("[id^='tab']").hide(); // Hide all content
          $("#tabs li").attr("id",""); //Reset id's
          $(this).parent().attr("id","current"); // Activate this
          $('#' + $(this).attr('name')).fadeIn(); // Show content for the current tab
        }

        var tab = $(this).attr("name");
        localStorage.setItem("tab", tab);
      });

      var currTab = localStorage.getItem("tab");
      $('a[name="' + currTab + '"]').trigger("click");
    </script>
  </body>
</html>

This method uses local storage, which isn’t supported in all browsers.
http://diveintohtml5.info/storage.html

This working and after refresh is the tab before refresh on the page. I don’t see in URL ‘?tab1/2’ but i gues since is working I don’t need to bother about this?

Good that it’s working :slight_smile:

Yeah, I binned the query string method (although it would be my preferred method), as we would have been fighting your existing code to implement it.

Thank’s again for help.

And if I am understood you right this is not the best and prefered way to do it but is something for now and I should think to remake it in future? :slight_smile:

Well, the thing is that localstorage is not supported by all browsers, so depending n what you want to support, that could be an issue for you.
Also, using a query string would allow your users to bookmark a certain tab directly.

Having said that though, if it works for you and browser support is not an issue, then you’re good :slight_smile:

Great!
I think we are done here! Thank’s and have a nice day!

You, too :slight_smile: