0

Question. I have some tabs and I would like to be able to link back to a specific tab from another page and make it the active tab. How should I do it?

HTML:

<div id="tabs-container">
            <ul class="tabs-menu">
                <li class="current"><a href="#tab-1"><strong>Tab 1</strong></a></li>
                <li><a href="#tab-2"><strong>Tab 2</strong></a></li>
                <li><a href="#tab-3"><strong>Tab 3</strong></a></li>
                <li><a href="#tab-4"><strong>Tab 4</strong></a></li>
            </ul>

            <div class="tab">
                <div id="tab-1" class="tab-content">Content1</div>
                <div id="tab-2" class="tab-content">Content2</div> 
                <div id="tab-3" class="tab-content">Content3</div>
                <div id="tab-4" class="tab-content">Content4</div>
            </div>   

</div>

JavaScript

$(document).ready(function() {
    $(".tabs-menu a").click(function(event) {
        event.preventDefault();
        $(this).parent().addClass("current");
        $(this).parent().siblings().removeClass("current");
        var tab = $(this).attr("href");
        $(".tab-content").not(tab).css("display", "none");
        $(tab).fadeIn();
    });
});

Thanks in advance :)

Wai
  • 1
  • 1

1 Answers1

0

You can use URL parameters for that :

function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split('&'),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split('=');

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};

$(function(){
    var toGet = getUrlParameter('tab');
    $(".tab-content").not('#'+toGet).css("display", "none");
    $("#"+toGet).fadeIn();
});

With a URL like http://....?tab=tab-1

Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • Hmm... the tab content changed but however the current tab doesnt light up. anyway to fix that? – Wai Jun 04 '17 at 11:24
  • Oh... and it doesn't work on chrome. when i use chrome, the anchor link landed on the correct tab. however, chrome auto added #tab1 behind it... – Wai Jun 04 '17 at 11:55
  • Can you please give me the full code you are using? Mine code works fine when I test it. – Zenoo Jun 04 '17 at 12:38
  • Hmmm... sorry sorry. it suddenly works now. Thanks for your help – Wai Jun 04 '17 at 13:05
  • No problem. Don't forget to validate the answer if everything is set. – Zenoo Jun 04 '17 at 13:14