I have a div which located at the bottom of the page:
<div id="myDiv"></div>
I want to go to this div after performing of my JS-function. In other words, I want to have my url become myurl#myDiv
and to go to my div. But without reloading the page. How this can be done using JavaScript? Unfortunately I have not found a working solution for this issue. I am not using any JS-libraries and frameworks.
The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.
Scrolling to an element can be achieved in Javascript using the scrollIntoView() method. Smooth animation and customizing the alignment can be set through the scrollIntoViewOptions parameter.
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.
To scroll to a particular element, use, scrollIntoView, supported by IE6+ and real browsers:
document.getElementById('myDiv').scrollIntoView();
Check window.location.hash
on DOMReady, to see if there is a hash in the URL matching any element in your document.
If there are #myDiv
links within the document, you would need to add onclick
listeners to them, perform the scroll manually, as per the code above, and return false
to avoid following the link to #myDiv
.
Demo
Try setting the window's location to that of the ID. The browser will then scroll to that element.
window.location.hash = '#myDiv';
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