SitePoint Sponsor

User Tag List

Results 1 to 18 of 18
  1. #1
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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:
    Code:
    <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
    Code:
    <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>

  2. #2
    SitePoint Addict bronze trophy
    Join Date
    Sep 2005
    Posts
    317
    Mentioned
    5 Post(s)
    Tagged
    0 Thread(s)
    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!

  3. #3
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Patche View Post
    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.

  4. #4
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    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:

    Code:
    <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:

    Code:
    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/9...-in-javascript

    HTH

  5. #5
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    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:

    Code:
    <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:

    Code:
    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/9...-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..

  6. #6
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Maybe trigger a click on them?

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

  7. #7
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry but nothing happen. Doesn't even change the URL when I try like this
    Code:
            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
    Code:
     <ul id="tabs">
            <li><a href="?tab=1" name="tab1" >tab1</a></li>
            <li><a href="?tab=2" name="tab2" >tab2</a></li>
        </ul>

  8. #8
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Can you post enough code that I can recreate your tabs.
    Please only post HTML, JS and CSS (no PHP).

  9. #9
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    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
    Code:
    <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
    Code:
    <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
    Code:
    #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);
    }

  10. #10
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Remove this line from your click handler:

    Code:
    e.preventDefault();

  11. #11
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

  12. #12
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    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:

    Code:
    $("#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:

    Code:
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>Accordion</title>
      </head>
    
      <body>
        <ul id="tabs">
          <li><a href="#" name="tab1" >Снимки</a></li>
          <li><a href="#" name="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>
        </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

  13. #13
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    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:

    Code:
    $("#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");

    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?

  14. #14
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    Good that it's working

    Quote Originally Posted by slsv View Post
    I don't see in URL '?tab1/2' but i gues since is working I don't need to bother about this?
    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.

  15. #15
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    Good that it's working
    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?

  16. #16
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    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

  17. #17
    SitePoint Enthusiast
    Join Date
    Feb 2014
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Pullo View Post
    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
    Great!
    I think we are done here! Thank's and have a nice day!

  18. #18
    Gre aus'm Pott gold trophysilver trophybronze trophy
    Pullo's Avatar
    Join Date
    Jun 2007
    Location
    Germany
    Posts
    5,938
    Mentioned
    214 Post(s)
    Tagged
    12 Thread(s)
    You, too


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •