Trigger an event when page is loaded with a unique id (anchor link)

I need a button to be triggered on page load. Which I’ve figured out how to do with a window.onload function.

But what I need to figure out is how to trigger this only when the page is loaded from a unique id (eg the button would be auto clicked when visited from , but not triggered when visited from

I don’t know js much at all, so I’m not sure if this is even possible?

Thank you.

24 thoughts on “Trigger an event when page is loaded with a unique id (anchor link)”

  1. It is pretty common to come across answers with javascript for a jquery question, because for simplicity sake. Since it is easily achieved using JavaScript.

    var location = window.location.pathname; //returns /#xyz/index.html

    Please note that it is recommended not to use $(location) in jquery which may not provide an expected behaviour.


    Please read this post Get current URL with jQuery? to get much clearer idea about JS and JQuery comparison for best practices.
    I included the answer to keep it clear and link for more explanation.

  2. Sounds like you need an if statement!

    if(location.hash === "#xyz") {
        /// Do stuff

    There isn’t an event for "when the URL hash becomes a specific value". There are events for "page loaded" and for "url hash changed", and any check more specific than that needs to be handled by putting an if statement in one of those events.


Leave a Comment