How to jump to a specific div which placed bottom of page using JavaScript?

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.

Answers


Try setting the window's location to that of the ID. The browser will then scroll to that element.

window.location.hash = '#myDiv';

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


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


Need Your Help

iOS10 UNNotificationServiceExtension not called

ios apple-push-notifications ios10

Im implementing new iOS10 extension to use rich notifications. Im trying to test it on push notifications but is not working, I just receive a simple notification and is not going through the exten...

Search for a string or part of string in PHP

php arrays search store product

I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search in PHP and it seems that...