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?

2
  • 2
    if( location.href.includes("#") ) doSomething(); ? Commented Oct 22, 2021 at 15:50
  • @JeremyThille I would probably use location.hash Commented Oct 22, 2021 at 15:52

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Glad it worked. If this solved your problem, please accept it as the answer. :)
2
var hash = window.location.hash;
if(hash){
// do something
}

Comments

0
<script>
  if (window.location.href.includes('#')) {
    // run your code here
  }
</script>

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.