4

I am trying to open specific bootstrap tab from clicking on an external link.

<ul class="nav nav-tabs">
  <li><a href="#profile" data-toggle="tab">Profile</a></li>
  <li><a href="#message" data-toggle="tab">Messages</a></li>
</ul>

<div class="tab-content">
  <div class="tab-pane" id="profile">Contents</div>
  <div class="tab-pane" id="message">Contents</div>
</div>

// Out side link which is place on different page: 
<a href="index.php?p=edit-profile#profile">Profile Link From Outside</a>

This is how I tried it using jquery:

// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
})

This is opening my tabs correctly. But my problem is when it open page scroll to the top of the page. Is there a way to avoid from this problem?

I tied it with .scrollTop(); but I couldn't figure it out.

After adding .scrollTop(); my code lookk like this.

// Javascript to enable link to tab
var url = document.location.toString();
if (url.match('#')) {
    $('.nav-tabs a[href=#'+url.split('#')[1]+']').tab('show') ;
} 

// Change hash for page-reload
$('.nav-tabs a').on('shown.bs.tab', function (e) {
    window.location.hash = e.target.hash;
    $('html,body').scrollTop(300);
});

Any idea would be highly appreciated. Thank you.

labilbe
  • 3,501
  • 2
  • 29
  • 34
user3733831
  • 2,886
  • 9
  • 36
  • 68
  • 1
    Perhaps it scrolls up to the tab? If that is the case you may change the id with class or prevent the default behaviour of the links. – Mariy Jul 20 '15 at 14:07
  • Try adding `e.preventDefault();` on `shown.bs.tab` event. – D4V1D Jul 20 '15 at 14:14
  • possible duplicate of [How to stop default link click behavior with jQuery](http://stackoverflow.com/questions/5632031/how-to-stop-default-link-click-behavior-with-jquery) – D4V1D Jul 20 '15 at 14:16
  • @D4V1D. I checked it.. but problem is still same. – user3733831 Jul 20 '15 at 14:17
  • updated code - ` $('.nav-tabs a').on('shown.bs.tab', function (e) { e.preventDefault(); window.location.hash = e.target.hash; $('html,body').scrollTop(300); });` – user3733831 Jul 20 '15 at 14:18
  • my url is like this - `index.php?p=edit-profile#profile` so when page is reloading tabs display top of the browser window. – user3733831 Jul 20 '15 at 14:28

1 Answers1

1

I found that for Firefox I had to also add e.stopImmediatePropagation()

$('.nav-tabs li a').click(function(e){
  e.preventDefault();
  e.stopImmediatePropagation();
  $(this).tab('show');
});

Hope this helps

max kaplan
  • 541
  • 4
  • 13