massanisso massanisso - 1 month ago 6
Javascript Question

jQuery – Linking to page using data attribute

I have a simple dynamic tabbed gallery on page B using this code:

$('ul.tabs li').click(function(){
event.preventDefault();

var tab_id = $(this).attr('data-tab');

$('ul.tabs li > figcaption').removeClass('current');
$('.tab-content').removeClass('current');

$(this).find('figcaption').addClass('current');
$("#"+tab_id).addClass('current');
});


Suppose I have a link on page A that I want to link to page B with the corresponding tab on page B active. How would I go about doing that? I've been trying to research data attributes in href tags and I'm so confused.

Thanks!

Answer

Use the page hash to specify the initial tab of the page. So if you want tab3 to be displayed, use a link like:

<a href="page_b.html#tab3">...</a>

On page B, check for the hash at page load time:

$(document.ready(function() {
    var hash = window.location.hash;
    if (hash) {
        $('ul.tabs li > figcaption, .tab-content').removeClass('current');
        $(hash).addClass('current');
        $('ul.tabs li[data-tab=' + hash.substr(1) +'] figcaption').addClass('current');
    }
    ...
});