简体   繁体   中英

Scroll to element using data-attributes

I'm trying to figure out how I can have the element scroll to a particular element using data-attributes if it matches the ID instead of using anchor tags. Here is what I'm working.

Once the user clicks on a button it will show the content and also scroll to that particular element that matches the data-attributes. I can't seem to make it scroll

<div class="container">
    <div class="post" data-id="content-one">
        post one
    </div>
    <div class="post" data-id="content-two">
        post two
    </div>
</div>
<div class="container-two">
    <div id="content-one" class="post-content" >
      content one
    </div>
    <div id="content-two" class="post-content" >
      content two
    </div>
</div>
$(".container .post").on('click', function() {
    var data_id = $(this).data('id');
    $('.post-content').each(function() {
        var el = $(this);
        if (el.attr('id') == data_id)
            el.show();
        else
            el.hide();
    });
    $('html, body').animate({
        scrollTop: $(data_id).offset.top()
    }, 'slow');
});

https://jsfiddle.net/clestcruz/vf4ufg6b/

Concatenate a # to the id to make a proper selector. Also the use .offset().top because offset() is a function which returns an object which contains current position of the element. Then we can access it using the top key.

$('html, body').animate({
    scrollTop: $( '#' + data_id).offset().top
}, 'slow');

DEMO

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