clestcruz
clestcruz

Reputation: 1111

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/

Upvotes: 3

Views: 9470

Answers (1)

rrk
rrk

Reputation: 15846

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

Upvotes: 7

Related Questions