19

I'm using a TAB navigation for my subpage Products -> ?p=products (see code below, website is realized with HTML and PHP)

The problem:

The user clicks, for example, in the second TAB the link Details. Then he uses the back button. Now he comes back to the Product site, but not in the second tab, rather in the first.

I would like to remember the last used tab (here: href="#section-2"), if the user goes back to the product page.

How can I realize this?

<div id="tabs" class="tabs">
    <nav>
        <ul>
            <li><a href="#section-1" class="icon-cross"><span>Product 1</span></a></li>
            <li><a href="#section-2" class="icon-cross"><span>Product 2</span></a></li>
            <li><a href="#section-3" class="icon-cross"><span>Product 3</span></a></li>
            <li><a href="#section-4" class="icon-cross"><span>Product 4</span></a></li>
        </ul>
    </nav>

    <div class="content">

        <section id="section-1">
            <div class="tab-heading">
                <hr>
                <h2 class="intro-text text-center"><strong>Product 1</strong></h2>
                <hr>
            </div>
            ...
        </section>

        <section id="section-2">
            <div class="tab-heading">
                <hr>
                <h2 class="intro-text text-center"><strong>Product 2</strong></h2>
                <hr>
            </div>

            <a href="?p=details">Details</a>

        </section>
    </div>
</div>
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sebastian
  • 377
  • 1
  • 2
  • 17
  • Please post a working fiddle if you want to get this sorted quickly – Parag Jadhav May 31 '17 at 17:39
  • It depends on how you want to solve it (also did you implement the tabs or are you using some kind of plugin?) a working fiddle would be good to move on from there. Either way, on what it depends: I see 2 possible ways. One is: append the active tab to the url. The pro of this approach is you then later can render which tab is active on the server. The other way is save it in a cookie or localstorage and always update the last active tab. Then via javascript if the page gets loaded and the site contains the active tab id voilà -> open tab – caramba May 31 '17 at 17:45
  • You can use [Cookies](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) or [sessionStorage](https://developer.mozilla.org/en/docs/Web/API/Window/sessionStorage) – nekiala Jun 02 '17 at 23:08
  • Are you using a library for tabs or have you coded it all? – Parantap Parashar Jun 03 '17 at 08:08

5 Answers5

15

You can use sessionStorage to store (while the user's browser is open) the last used tab and retrieve each time the page loads:

$(document).load(function(){
   if (sessionStorage.getItem('lastsessionid') != null){
       //go to anchor, simulates the link click
       $(document).scrollTop( $(sessionStorage.getItem('lastsessionid')).offset().top );
   }
   $('a[href=#section*]').on('click', function(){
       sessionStorage.setItem('lastsessionid', this.href);
   });
});

EDIT: Woooow, it turned into so highly voted answer, I'll improve it. The main idea of my solution is to not reinvent the wheel about the W3C standards about anchor, not only what W3C expect (some browsers it's way ahead of those standards), but what the programming common sense expect from it. IMHO, the most important thing when you're overcoming an attribute's limitations is to try to continue their natural behavior, avoiding 'magic' features and other piece of codes that will become hard to maintain in the future. What the OP needed was to store some kind of value to use after and just that.

Other approach that would be common it's to use trigger techniques, but I strongly recommend to avoid triggers because you're simulating user's interaction unnecessarily and, sometimes, the application has other routines associated with the element's click event where can turn the use of clicking bothersome. It's true that the way I did the anchor behavior was simulated too, but, well, in the end it's my coding culture to avoid triggers to maintain the nature of event's calls:

$(document).load(function(){
   if (sessionStorage.getItem('lastsessionid') != null){
       //go to anchor, simulates the link click
       $(sessionStorage.getItem('lastsessionid')).trigger('click');
   }
   $('a[href=#section*]').on('click', function(){
       sessionStorage.setItem('lastsessionid', this.href);
   });
});

To some kind of information, in the old times the web devs (I'm not so old, but I programmed before the javascript turned in so great tool into web dev. routine) couldn't rely so much on scripting techniques, so what they do to propagate some kind of behavior has store that anchor into some post/get variable and perpetuate that value until the user reaches the desired routine, forcing way through the link to load with an #{$desiredAnchor} to force the anchor behavior. Obviously it is a method that has its flaws and blind spots, but was very common when the javascript was not the big role into the industry. Some devs can need that idea when working in such small pads from department store, per example, where the pad's browsers is too old to work well with javascript ES4/ES5/ES6 new functions.

capcj
  • 1,535
  • 1
  • 16
  • 23
2

If I understood you correctly I would simply create a session that stores the click. You can accomplish this quickly and easily using ajax to register when the click was made and remotely set a session. This session will be replaced every time the user clicks a tab. This will continuously maintain a session of the last tab clicked. Here is the structure of the three elements needed:

1. The tabs section you have placed in this question (HTML)

2. Ajax post sending the tab selected to remote file for session storage (JS)

3. The remote file that will receive the tab value to store in session (PHP)


AJAX POST This snippet will listen for the user to click the tab then send the value selected to php file for saving. You can place this into a separate file or directly in the footer of your page. Make sure to have jquery working on your page.

$(".icon-cross").on("click",function(){
   var tabValue = $(this).attr('href');
   $.post('file-to-save-session.php', {tabSel: tabValue}, function(data){
       console.log(data);
   });
});

Quick explanation... we listen for the tab with class (icon-cross) to be click, we then store the value of the href attribute into var tabValue. Then we post the value via ajax to the php file for saving. Once it is saved it will echo the retrieved value and the function will display it in the console for viewing and debugging.


PHP FILE - SAVE TAB SELECTION This file can be stored anywhere in your file system, just make sure to point the path correctly in the ajax request.

<?php 

session_start(); 

if(isset($_POST['tabSel']) && $_POST['tabSel'] != ''){
   $_SESSION['selected_tab'] = $_POST['tabSel'];
   echo $_SESSION['selected_tab'];
}else{
   echo 'NO TAB SELECTION RECEIVED!';
}

?>

This is pretty self explanatory. It is listening for a post to the page with the variable sent via ajax post. If the post is sent and the post is not empty it will store the value to the session. If not it will return nothing and not touch the session itself.


YOUR HTML FILE WITH TABS Last but not least you can now add this code snippet to the top of your page to see the value of the last selected tab by the user. This would go on the page where your tabs are. You may need to convert html file into php if it is not already

<?php 
session_start(); 

if(isset($_SESSION['selected_tab'])){ 
    echo $_SESSION['selected_tab']; 
}
?>

Now you will be able to see the previously selected tab on your page. You can store it into a php variable or simply place the session into an if statement to highlight or display the last selected tab.

Hope this helps! Let me know if you need anymore help on the matter :).


UPDATE: OVERRIDE THE JAVASCRIPT BEING ADDED BY PLUGIN: Add this to the bottom of your page (under all js files)

<?php if(isset($_SESSION['selected_tab'])){ ?>
    <script>
       $(".icon-cross").removeClass('tab-current');
       $("section").removeClass('content-current');
       $('[href="<?php echo $_SESSION['selected_tab']; ?>"]').addClass('tab-current');
       $('section<?php echo $_SESSION['selected_tab']; ?>').addClass('content-current');
    </script>
<?php } ?>

The first two lines will remove the current class from all selected tabs and their headers, the second will add the class to the tab saved in the session. If there is no session, this code will not run.

lov2code
  • 394
  • 1
  • 6
  • 19
  • It works only partially. At the top left, the last selected tab is displayed correctly, but if I go back it does not select the corresponding tab. I guess that it is possibly the tab framework? I use this: https://tympanus.net/codrops/2014/03/21/responsive-full-width-tabs/ The tab also not changes if I enter the following link in the URL bar: http://127.0.0.1/?p=products#section-4 – Sebastian Jun 04 '17 at 17:24
  • If you look at the file source, are two tabs being selected? This could be cause because the framework is overwriting the tab selection. If there is a class being added to the selected tab check if the class is also being selected by another tab. For example I see that when a new tab is selected it adds the class="content-current" to the section. – lov2code Jun 12 '17 at 08:04
  • To override this at the very bottom of your page you can add the code I added here at the end of my answer. – lov2code Jun 12 '17 at 08:04
2

The problem is normal libraries for tabs do not preserve the hash of the link to the tab. So, your browser is unable to track the progress of tabs and hence the back button does not work in case of tabs as you expected.

So the idea is to preserve # link in href tab. If one is able to preserve that then browser will be able to track users progress through tabs and back button will land user on the previous tab.

You can store the # value in hash property of window.location.

See the answer below

Bootstrap 3: Keep selected tab on page refresh

This might have a solution for you.

After, you have preserved the hash and now able to work out the back button of the browser handle your transitions by capturing the onhashchange event of the javaScript.

Here, you can manage to change tabs when user hits back in the browser.

Hope this would help.

Parantap Parashar
  • 1,930
  • 1
  • 14
  • 22
2

Give id for each tab.Then ,

$(".icon-cross").click(function(){
    var selected_id= $(this).attr('id);
    //save this id to cookie.Then retrieve this cookie value on next page visit
})
Dhanesh
  • 324
  • 2
  • 14
0

I think you need look at this https://css-tricks.com/using-the-html5-history-api/

Abyss
  • 315
  • 2
  • 11
  • Answers should have explanations in enough detail for the OP to solve their issue. The link can then be used to credit the source at the bottom. – dennispreston Jun 07 '17 at 17:20