How to use window.location.hash?

The window.location.hash property is used to retrieve or set the fragment identifier (hash) in a URL. The fragment identifier is the part of the URL that comes after the “#” symbol, typically used for navigating within a page or identifying specific content.

To obtain the fragment identifier in the current URL, you can use the following syntax:

var hash = window.location.hash;

To set a fragment identifier in a URL, you can use the following syntax:

window.location.hash = "#section1";

After setting the fragment identifier, the page will automatically scroll to the element with the id attribute that matches the fragment identifier. Changes in the fragment identifier can be detected by listening for the hashchange event.

window.addEventListener("hashchange", function() {
    console.log("Hash changed to: " + window.location.hash);
});
Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds