Mish.k.a
Mish.k.a

Reputation: 299

Scroll top after showing a tab

I have Bootstrap tabs on my page, but when I click on it, the tabs are hidden. Is there a way to scroll the position up so the tabs can be seen? Nothing I have found helped me. I can't change positions of the tabs or use hidden anchors - the tabs are the anchor.

<ul class="nav nav-tabs" role="tablist">
    <li class="active bio" role="presentation"><a href="#bio" role="tab" data-toggle="tab">biografie</a></li>
    <li class="films hidden-sm hidden-md hidden-lg" role="presentation"><a href="#films" aria-controls="films" role="tab" data-toggle="tab">filmografie</a></li>
    <li class="trivia hidden-xs" role="presentation"><a href="#trivia" role="tab" data-toggle="tab">zajímavosti</a></li>
    <li class="awards hidden-xs" role="presentation"><a href="#awards" role="tab" data-toggle="tab">ocenění</a></li>
    <li class="videos hidden-xs" role="presentation"><a href="#videos" role="tab" data-toggle="tab">videa</a></li>
    <li class="gallery hidden-xs" role="presentation"><a href="#gallery" role="tab" data-toggle="tab">galerie</a></li>
    <li class="contact hidden-xs" role="presentation"><a href="#contact" role="tab" data-toggle="tab">kontakt</a></li>
</ul>

This is the JS I use to get to the anchors:

  $("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
    var id = $(e.target).attr("href").substr(1);
    window.location.hash = id;
  });

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

Page with tabs: http://testovani-frameworku.wz.cz/jennifer-lawrence.html#awards

Upvotes: 1

Views: 4373

Answers (2)

Mish.k.a
Mish.k.a

Reputation: 299

So this is how I've solved it. I've added "-tab" at the end of a tab's ID and the original ID has the link.

$("ul.nav-tabs > li > a").on("shown.bs.tab", function(e) {
    var id = $(e.target).attr("href").substr(1);
    id = id.substring(0, id.length-4);
    window.location.hash = id;    
});

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

Upvotes: 0

Fata1Err0r
Fata1Err0r

Reputation: 826

If you want to go to the very top, you could do it a couple ways

window.scrollTo(0, 0);

or

$("mySelector").animate({ scrollTop: 0 }, "fast");

or

$(window).scrollTop(0);

It just depends what type of effect you want. Could just set the scrollTop to 0 (which is very top) if you don't want animation effect. Could just use the vanilla JS window.scrollTo(x,y)

Hope this helps!

Upvotes: 1

Related Questions