I have few div
s .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?
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.
The scrollIntoView method: The scrollIntoView() is used to scroll to the specified element in the browser. Example: Using scrollIntoView() to scroll to an element.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With