Wednesday, June 7, 2017

Tab-Navigation - Remeber user selection

Leave a Comment

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.

Does anyone have an idea how I can 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> 

5 Answers

Answers 1

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.

Answers 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 :).

Answers 3

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.

Answers 4

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 }) 

Answers 5

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment