Skip to content

How to invoke javascript function when # is present in URL

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?

Answer

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