Javascript on change hash

How to Detect URL Hash Change in JavaScript (onhashchange)

We can detect the changes in URL hash value using JavaScript events. The fragment identifier in a URL that starts with the «#» symbol is known as the hash value.

JavaScript fires the hashchange and popstate events whenever the hash value in a URL changes. We can listen to these events to identify the changes in the URL hash in JavaScript.

When users add or change the URL hash in JavaScript without reloading the page, you can use any of these events to perform some functionalities.

Let’s see how can we listen to these events.

Detect URL Hash Change With JavaScript hashchange event

You have to call the addEventListener() method on the window object. We can attach the hashchange event with this method.

window.addEventListener("hashchange", () => < console.log("The hash value has changed"); >); 

If the current URL is https://example.com/post#comments in your browser, we can change the «#comments» to anything else like «#reviews» in the URL.

Читайте также:  Php классы конструктор значение

Whenever the value changes, the hashchange event will fire, and the callback function will execute.

You can get the hash value from the URL inside this callback function using the location object in Javascript.

Detect URL Hash Change With JavaScript popstate event

You can also use the popstate event using the addEventListener() method in JavaScript. This event gets fired when the hash value changes in the current URL.

window.addEventListener("popstate", () => < console.log("The hash value has changed"); >); 

You will call the addEventListerner() method on the window object and put popstate as the event name.

The callback function will be executed whenever the hash value changes in the URL. If you add a new value to the URL for the first time, JavaScript will also fire the event.

Conclusion

These are the 2 events in JavaScript that we can use to identify the changes in URL hash. It doesn’t matter which event you use in your project, you will get the same result.

You have to call the addEventListener() method on the window object. Then pass hashchange or popstate as the event name.

JavaScript will track the changes in hash value and execute the code from the callback function. This is how you can detect URL hash change in JavaScript.

Источник

Window: hashchange event

The hashchange event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("hashchange", (event) => >); onhashchange = (event) => >; 

Event type

Event properties

HashChangeEvent.newURL Read only A string representing the new URL the window is navigating to. HashChangeEvent.oldURL Read only A string representing the previous URL from which the window was navigated.

Event handler aliases

Examples

You can use the hashchange event in an addEventListener method:

.addEventListener( "hashchange", () =>  console.log("The hash has changed!"); >, false, ); 

Or use the onhashchange event handler property:

function locationHashChanged()  if (location.hash === "#cool-feature")  console.log("You're visiting a cool feature!"); > > window.onhashchange = locationHashChanged; 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

onhashchange Event

The numbers in the table specify the first browser version that fully supports the event.

Event
onhashchange 5.0 8.0 3.6 5.0 10.6

Syntax

In JavaScript, using the addEventListener() method:

Technical Details

More Examples

Example

How to assign the «onhashchange» event to the window object:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

JavaScript hashchange Event

Summary: in this tutorial, you will learn about the JavaScript hashchange event and how to handle it effectively.

Introduction to the JavaScript hashchange event

The URL hash is everything that follows the pound sign ( # ) in the URL. For example, suppose that you have the following URL:

https://www.javascripttutorial.net/javascript-dom/javascript-hashchange/#headerCode language: JavaScript (javascript)

The URL hash is header . If the URL hash changes to footer , like this:

https://www.javascripttutorial.net/javascript-dom/javascript-hashchange/#footerCode language: JavaScript (javascript)

The hashchange event fires when the URL hash changes from one to another. In this example, it changes from #header to #footer .

To attach an event listener to the hashchange event, you call the addEventListener() method on the window object:

window.addEventListener('hashchange',() =>< console.log('The URL has has changed'); >);Code language: JavaScript (javascript)

To get the current URL hash, you access the hash property of the location object:

window.addEventListener('hashchange',() => < console.log(`The current URL hash is $ `); >);Code language: JavaScript (javascript)

Additionally, you can handle the hashchange event by assigning an event listener to the onhashchange property of the window object:

window.onhashchange = () => < // handle hashchange event here >;Code language: JavaScript (javascript)

Summary

  • The hashchange event fires when the URL hash changed.
  • To register an event listener, you call the addEventListener() method or assign an event listener to the onhashchange property of the window object.

Источник

Managing the URL Hash with Javascript

The Javascript URL object can be used to get and set hash value of a given url. To detect a change in hash in the current url, the hashchange event can be listened to.

Getting the URL Hash

The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also.

If the url does not contains a hash, then an empty string «» will be returned.

var some_url = 'https://usefulangle.com/posts?123#slider' var hash = new URL(some_url).hash; // "#slider" console.log(hash); 
// document.URL refers to the current url var hash = new URL(document.URL).hash; console.log(hash); 

Changing the URL Hash

var some_url = 'https://usefulangle.com/posts?123#slider' var url_ob = new URL(some_url); url_ob.hash = '#reviews'; // new url string var new_url = url_ob.href; // "https://usefulangle.com/posts?123#reviews" console.log(new_url); 
// document.URL is the current url var url_ob = new URL(document.URL); url_ob.hash = '#345'; // new url var new_url = url_ob.href; // change the current url document.location.href = new_url; 

Note that this will not cause a reload of the page.

Detecting Change in Hash of the Current URL

The window.hashchange event can be listened to know when the hash fragment in the current url changes.

window.addEventListener('hashchange', function() < // new hash value console.log(new URL(document.URL).hash); >); 

Источник

Оцените статью