...">

How to go to a specific div that places the bottom of the page using JavaScript?

I have a div located at the bottom of the page:

<div id="myDiv"></div> 

I want to go to this div after executing my JS function. In other words, I want my url to become myurl#myDiv and go to my div. But without reloading the page. How can this be done using JavaScript? Unfortunately, I did not find a working solution for this problem. I do not use JS libraries and frameworks.

+4
source share
3 answers

Try setting the window location with respect to the identifier. Then the browser will go to this element.

 window.location.hash = '#myDiv'; 
+7
source

To jump to a specific 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 of your document.

If the document has #myDiv links, you need to add onclick listening to them, manually scroll according to the code above, and return false to avoid the link to #myDiv .

Demo

+19
source

The scrollIntoView (true) method also accepts a parameter that indicates whether to align top (true) or bottom (false).

+3
source

Source: https://habr.com/ru/post/1432494/


All Articles