Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to a specific div

I have few divs .posts which have a attr data-id which corresponds to the mysql DB id.

<div class="posts" data-id="1"></div>
<div class="posts" data-id="2"></div>

Now if I want to scroll to a specific div which I am only known to the data-id. How will I scroll to it?. My JSFiddle is here. Can anyone give an example along with a JSFiddle?

like image 609
user3508453 Avatar asked May 21 '14 14:05

user3508453


People also ask

How do you jump a div in HTML?

By prepending your href with # , you can target an HTML element with a specific id attribute. For example, <a href="#footer"> will navigate to the <div id="footer"> within the same HTML document. This type of href is often used to navigate back to the top of the page.

How do I scroll to a specific div?

The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.

How do you scroll to a particular div in react?

To scroll to an element on click in React:Set a ref prop on the element you want to scroll to. Set the onClick prop on the other element. Every time the element is clicked, call the scrollIntoView() method on the ref object.

How do I scroll to a specific section in HTML?

But we can make it scroll smoothly to the desired section as well. To do this, we can use the following line in our code: scroll-behavior: smooth; There are other scroll behaviours also defined in HTML, you can go here for details about them.


1 Answers

You use link anchors and JQuery. Just give your link the class "scroll" and use the following code in the head:

$(function() {
  // Listen for a click event on the anchor
  $('.scroll').click(function(event) {
  
    // Prevent the jump to target that is default browser behavior
    event.preventDefault();
    
    // Animate the scrollTop property of the scrollParent to the top offset 
    // of the target element. In this case, we have an animation duration of 1000ms(1 second).
    $('html').animate({
      scrollTop: $(this.hash).offset().top
    }, 1000);
  });
});
/* Just for demo purposes */
.post {
  margin: 100vh 0;
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="#anchor" class="scroll">Go To Div 8</a>
<div class="post" id="anchor">Scroll to me</div>
like image 63
Jacob Gray Avatar answered Sep 27 '22 18:09

Jacob Gray