-3

I have a HTML page which has horizontal tabs defined as follows

<ul class="tabs clear has-borderbottom">
    <li class="js-tab selected" data-tab="tab1"><a href="#">TAB 1</a></li>
    <li class="js-tab" data-tab="tab2"><a href="#">TAB 2</a></li>
    <li class="js-tab" data-tab="tab3"><a href="#">TAB 3</a></li>
 </ul>

When I load the page it opens with TAB 1 opened which is ok for me in all cases. But there is one condition where I want to load TAB 2 as the opening tab instead of tab 1. How can I do this programatically in js?

I use window.location.href = "/details to redirect to the above HTML page where I want to display TAB 2 opened be default.

Cœur
  • 37,241
  • 25
  • 195
  • 267
codec
  • 7,978
  • 26
  • 71
  • 127

1 Answers1

0

You can try to give a parameter with your window.location.href = "/details?tab=2". Then you can read your GET-Parameter out of the Location with the function posted in: How to retrieve GET parameters from javascript?

function findGetParameter(parameterName) {
    var result = null,
        tmp = [];
    location.search
    .substr(1)
        .split("&")
        .forEach(function (item) {
        tmp = item.split("=");
        if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
    });
    return result;
}

Then you have to change your selected-Class onload of the document. Add a new document.onload-Function, like this:

function doThisOnOnload()
{
  var selected = findGetParameter("tab");
  
  $('.js-tab').removeClass("selected");
  $('[data-tab="tab'+selected+'"]').addClass("selected");
}

Therefor jquery has to be injected.

Community
  • 1
  • 1
Merschi
  • 56
  • 1
  • 5
  • tab2 does get selected (highlighted) but it does not switch the tab. I can still see tab1 with tab2 underlined(highlighted). – codec Oct 25 '16 at 11:31
  • Then we need to know your javascript, how does it work now? – Merschi Oct 25 '16 at 13:11