1

I know this question has been answered but the scenario of my question is quite different, so I will try to explain it. If anyone wants more explanation I would love to give it.

I have a filter bar that consists of 8 boxes.

 <div class="filter-box  filter-box--green px-2 pt-3 pb-4" data-box-id="web-dev">
     <img width="60" height="60" src="{!! asset('images/Service-page/Web Development-hover.svg') !!}" alt="Web Dev" />
         <div class="title text-center mt-2 pb-4">
                            Web<br />Development
         </div>

         <div class="arrow">
             <img src="{!! asset('images/Service-page/Green.svg') !!}">
         </div>
  </div>

When I am clicking on the box, it scrolls to the specific div based on the data-box-id

Below is the JavaScript code that scrolls to the particular div.

    <script type="text/javascript">
    $(document).ready(function() {
        $('.filter-box').on('click', function(e) {
            // console.log(window.scroll)
            var boxId = $(this).attr('data-box-id');

            $('html, body').animate({
                scrollTop: $("#" + boxId).offset().top
            }, 'slow');
        });
    })
</script>

Here I used offset. The problem is that sometimes, the cursor is not at target. What I want to achieve is that when I click anywhere on the filter box, it should scroll and my cursor position should be on the expected div.

aldi
  • 718
  • 1
  • 8
  • 22
Malik Awan
  • 115
  • 15

1 Answers1

2

Use Jquery .animate to have a smooth scroll to the desired element see the example.

$( "#notelement" ).click(function() {
  $('html, body').animate({
      scrollTop: ($('#element').offset().top)
  },500);
});
#notelement{
  margin-bottom:800px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="notelement">Other element</div>
<div id="element">Scroll to element</div>
g4ost
  • 100
  • 8