简体   繁体   中英

Scroll to affix default position when links in container clicked

I made a tabbed contents using Jquery UI, and I got to make the tab selectors in fixed position using Bootstrap Affix . Similar to the way Yahoo uses, for each tab selector link clicked, it triggers the scroll page to selectors default position in order to show tab content from the start.

Code snippet: http://jsfiddle.net/rpgrhhnt/1/

<div class="news-tickers scrollspy" id="scrollToHere">

<ul class="catselector affix-top" data-spy="affix">
    <li><a id="foo" href="#cat1">Category 1</a></li>
    <li><a id="foo" href="#cat2">Category 2</a></li>
    <li><a id="foo" href="#cat3">Category 3</a></li>
</ul>

<div id="cat1">cat1 content</div>
<div id="cat2">cat2 content</div>
<div id="cat3">cat3 content</div>

</div>

Using JQuery scrollTop, I managed to get the process for the first selector link (Category 1) to work when other tab selectors are active. Other selector links don't scroll to start when clicked!

$('#foo').click(function () {
    $('html,body').animate({
        scrollTop: $("#scrollToHere").offset().top
    }, 800);
});

Any help is appreciated. :)

First of all - html elements should have unique ids. I've replaced href with expando attribute data-pos which have a jQuery selector for scroll-to-element. So <a id="foo" href="#cat1">Category 1</a> look like <a class="foo" data-pos="#cat1">Category 1</a> for now, and transform part of your JS to:

$('.foo').click(function () {
    var posElement = $($(this).data("pos"));
    $('html,body').animate({
        scrollTop: posElement.offset().top
    }, 800);
});

You can check out the result of these manipulations in jsFiddle

Update with affix and scrollspy: jsFiddle

Update with tabs with scroll effect: jsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM