middlelady
middlelady

Reputation: 583

Jquery .hash doesn't work on bootstrap tabs

I have a page with bootstrap tabs which I'd like to link from external pages. So I can immediately access the content of my interest.

Even though I read many questions in matter I can't really reach the goal. I've written this code which is not working for me:

var hash = document.location.hash;
if (hash) {
    $('.nav-tabs a[href='+hash+']').tab('show');
} 
// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
});

And my HTML is the following

<ul id="profile-tabs" class="nav-tabs">
    <li class="active"><a href="<?php echo get_permalink(); ?>#general-informations" data-toggle="tab"><?php _e("General Info",'Mytheme');?></a></li>
    <li class=""><a href="<?php echo get_permalink(); ?>#other" data-toggle="tab"><?php _e("Other",'Mytheme');?></a></li>
</ul>

I'm thinking that maybe I'm using .hash in the wrong way. Can you help me or suggest similar answers? I mean I've read almost all those without success. Thanks.

Upvotes: 0

Views: 129

Answers (1)

Jim
Jim

Reputation: 3579

Your CSS selector is incorrect. You are trying to match apples and oranges.

If your first anchor tag's href attribute was set to http://localhost/somehwhere/#general-informations and your URL bar ended with #general-informations then your CSS selector, a[href='+hash+'], would be attempting to do a direct match. Unfortunately the string http://localhost/somehwhere/#general-informations is not equal to the string #general-informations.

What you want is the CSS ends with selector: $=, use this:

$('.nav-tabs a[href$="'+hash+'"]').tab('show');

This will select all anchor tags with an href attribute that ends with the value of the hash variable.

Upvotes: 1

Related Questions