Managing the URL Hash with Javascript

PHOTO EMBED

Thu Jun 23 2022 15:32:32 GMT+0000 (Coordinated Universal Time)

Saved by @lancerunsite #jquery #event #change #hash #url

//Get hash of a given url

var some_url = 'https://usefulangle.com/posts?123#slider'

var hash = new URL(some_url).hash;

// "#slider"
console.log(hash);

//
//
//


//Get hash of the current url

// document.URL refers to the current url
var hash = new URL(document.URL).hash;

console.log(hash);



//
//
//


//Change hash of a given url

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);


//
//
//


//Change hash of the current 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;


//
//
//

/*
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);
});
content_copyCOPY

https://usefulangle.com/post/298/javascript-url-hash