Scroll to element using data-attributes

by Clest Dela Cruz

HTML

<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>

CSS

html, body {
  width: 100%;
  height: 100%;
}

.container {
  float: left;
  width: 100%;
  height: 100%;
  background-color: #ccc;
}

.container-two {
    float: left;
    width: 100%;
    height: 100%;
    background-color: beige;
}

.post:hover {
  cursor: pointer;
}

.post-content {
  display: none
}

JavaScript

$(".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');
});