Home > Mobile >  How to invoke javascript function when # is present in URL
How to invoke javascript function when # is present in URL

Time:10-23

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?

CodePudding user response:

var hash = window.location.hash;
if(hash){
// do something
}

CodePudding user response:

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";
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

CodePudding user response:

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

  • Related