Search code examples
javascriptjquerypushhistoryhashchange

JS/JQUERY TAB with history, compatibility


Ok I have a website which have several tabs showing different things. I did a very simple thing to manage tabs:

HTML:

<li id="thing1" class="tab selected"></li>
<li id="thing2" class="tab"></li>
<li id="thing3" class="tab"></li>

<div id="_thing1" class="box"></div>
<div id="_thing2" class="box hidden"></div>
<div id="_thing3" class="box hidden"></div>

JS/JQUERY:

$(".tab").on('click', function() {
        $(".tab").removeClass('selected');
        $(this).addClass('selected');
        $(".box").addClass('hidden');
        $( '#_' + $(this).attr('id') ).removeClass('hidden');
    }); 

Everything works fine, but I'm trying to add history to my tab click, so when you click back on your browser, you go to the last tab you've visited.

I've done some research, and i'm a little confused, it seems a lot of things i need to achieve my goal are not compatible with all browser. Jquery has not implemented things related to history.

for example : on('hashchange') is not compatible with every browser it seems.

This is what I started:

$(".tab").on('click', function() {
history.pushState({id: $(this).attr('id')}, $(this).attr('id'), '#'+$(this).attr('id'));
}

So is there any way I can achieve what i want, without plugins, and easily?


Solution

  • Ok this is what i finally did, if it could help someone:

    HTML:

    <li id="thing1" class="tab first selected"></li>
    <li id="thing2" class="tab"></li>
    <li id="thing3" class="tab"></li>
    
    <div id="_thing1" class="box"></div>
    <div id="_thing2" class="box hidden"></div>
    <div id="_thing3" class="box hidden"></div>
    

    JS:

    var realclick = true; // prevent adding history on hashchange
    
    $(".tab").on('click', function() {
        id = $(this).attr('id');
        $(".tab").removeClass('selected');
        $( '#' + id).addClass('selected');
        $(".box").addClass('hidden');
        $( '#_' + id ).removeClass('hidden');
        if (realclick) {
            history.pushState(null, null,  '#'+id);
        }
    }); 
    
    $(window).on('hashchange', function(e){ // triggered by browser, previous and next button
        var id ='';
        realclick = false;
        if (location.hash!='') { // if has hash
            id = $(location.hash+".tab").attr('id');
            $('#'+id).click();
        }
        else { // no hash = initial page
            id = $(".first.tab").attr('id');
            $('#'+id).click();
        }
        realclick = true;
    });
    

    If someone has some improvements to share, be welcome! I need to simulate click on my tab because some of them have others events attached to them and i need to keep them.