0

I am trying to call JavaScript function when # is present in URL. I know normal behavior is to navigate / scroll to the specific tag. But could not find how to invoke a JavaScript function.

The below example is close but not solving my problem.

What is the meaning of # in URL and how can I use that?

James Z
  • 12,209
  • 10
  • 24
  • 44
Aniruddha
  • 55
  • 2
  • 10

4 Answers4

2
var hash = window.location.hash;
if(hash){
// do something
}
Ahmed Hany
  • 952
  • 6
  • 12
2

You might be able to leverage the hashchange event to trigger the function, assuming you don't just want to keep polling the location to see if it changes.

DOCS: https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event

This code snippet will add the listener to the current page, then manipulate the hash and fire the function, displaying the new hash value. You could call any function here.

window.addEventListener('hashchange', function() {
    alert(location.hash);
});

window.location += "#test";
Chris Strickland
  • 3,388
  • 1
  • 16
  • 18
  • Thanks Chris. This is what I was looking for. Checking of hash on load still to be done for first time. But after that this is the thing I require. Thanks for your support. – Aniruddha Oct 22 '21 at 16:29
  • Glad it worked. If this solved your problem, please accept it as the answer. :) – Chris Strickland Oct 22 '21 at 17:06
0
<script>
  if (window.location.href.includes('#')) {
    // run your code here
  }
</script>
cs641311
  • 178
  • 8
0

use a location.hash function will solve your problem

var hash = window.location.hash.replace(/#/g, '');
if(hash){
// found a hash
console.log("heyy I found a hash")'
}
else{
// did not find a hash
console.log("Uh oh")
/*
  try using :
  window.location = window.location + '#' + "some random variable"
  to create a new URL and every time the page loads find the hash and 
  display the wanted data.
*/
}

PS: this only works if your URL is like example.com/#xyz then it will give you xyz as a console output. This may sound vague but if you do this you may get a Idea

Adhvaith Prasad
  • 129
  • 1
  • 6