Reputation: 1274
I have a seemingly simple problem to which I wasn't able to find a solution today. How can I create a bookmark (i.e., example.com/somepage#mybookmark) which automatically opens up elements under a JavaScript tab, such as the tabs suggested for use on w3schools?
I've tried assigning some id
s to the <li>
elements forming the tabs, e.g:
<li id="mybookmark"><a href="#" class="tablinks" onclick="openCity(event, 'London')">London</a></li>
and even an anchor name, e.g:
<li><a name="mybookmark" href="#" class="tablinks" onclick="openCity(event, 'London')">London</a></li>
but the best result I got so far when trying example.com/somepage#mybookmark was only to highlight the tab, without opening the content associated to it (which is what I actually want).
I presume that the answer lies in some JavaScript code, but could someone suggest how it should look?
Upvotes: 0
Views: 581
Reputation: 3345
Try something like this:
$(function () {
$(".tab-content").hide().first().show();
$(".yourNav li:first").addClass("active");
$(".yourNav a").on('click', function (e) {
e.preventDefault();
$(this).closest('li').addClass("active").siblings().removeClass("active");
$($(this).attr('href')).show().siblings('.tab-content').hide();
});
var hash = $.trim( window.location.hash );
if (hash) $('.inner-nav a[href$="'+ hash + '"]').trigger('click');
});
Basically you would be forcing the .click()
of the tab based on the url form the #
on. The top portion of this you said you already have, i.e. tabs opening fine and all that, its the second part where the var hash =
is declared. Let me know and good luck.
Upvotes: 1