javascript – Stay on same tab after Refresh

Question:

I'm developing a website in jQuery. And so far I've created a simple menu with content to appear inside divs.

Menu

<ul class="menu" id="menu">
    <li class="menu-text"><h4>Titulo</h4></li> 
    <li class="current"><a href="#1" data-id="div1">Menu1</a></li>
    <li><a href="#2" data-id="div2">Menu2</a></li>
    <li><a href="#3" data-id="div3">Menu3</a></li>
</ul>

Content in Div's

<div class="pbox" id="div1"> ... </div>
<div class="pbox" id="div2"> ... </div>
<div class="pbox" id="div3"> ... </div>

jQuery

$('#menu').on('click', 'a', function () {
    if(!($(this).closest('li').hasClass("current"))){
        $('.current').not($(this).closest('li').addClass('current')).removeClass('current');
        // fade out all open subcontents
        $('.pbox:visible').hide(600);
        // fade in new selected subcontent
        $('.pbox[id=' + $(this).attr('data-id') + ']').show(600);
    }
});

The only problem with using tabs (or tabs) is that when refreshing the page it automatically returns to the first tab, in this case #1 .

Is there any way, when refreshing, to stay on the same tab?

Answer:

Resolution:

After looking for help on the English stackoverflow, I managed to solve my problem. The final code looked like this:

jQuery

Select tab:

var menu = $('#menu');
    menu.on('click', 'a', function () {
    var current = $(this).closest('li');
    if(!current.hasClass("current")){        
    $('.current').removeClass('current');
    current.addClass("current");

    var id = $(this).attr('data-id');
    $('.pbox:visible').hide(600);
    $('#' + id + '.pbox').show(600);
    history.pushState(null, null, '#' + id);
  }
});

Continue on the same tab after refresh:

var menuId = location.hash.substring(1);
$( document ).ready(function() {
if (menuId) {
    var menu = $('#menu');
    var current = $("li[id='" + menuId + "']");
    if(!current.hasClass("current")){
    $('.current').removeClass('current');
    current.addClass("current");
    $('.pbox:visible').hide();
    $('#' + menuId + '.pbox').show(600);
    history.pushState(null, null, '#' + menuId);
}
}
});
Scroll to Top