0

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 example.com/#xyz , but not triggered when visited from example.com).

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

Thank you.

2 Answers2

1

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.

Brilliand
  • 13,404
  • 6
  • 46
  • 58
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.

$(location).attr('pathname');

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.

Yogesh C K
  • 34
  • 3
  • I think you forgot that the `#` sign has special behavior in URLs. URL hashes won't show up as part of the pathname. – Brilliand Feb 17 '21 at 00:53
  • Yes, thanks for pointing it out. let me edit my answer accordingly – Yogesh C K Feb 17 '21 at 05:44
  • Oh, that isn't how it works either. If the URL is "example.com/#xyz", then the pathname will simply be "/", because everything after the hash sign is moved into the `hash` variable rather than the `pathname` variable. Also the index.html won't be added, since that's strictly a detail of how the server works, not a part of the URL. – Brilliand Feb 17 '21 at 21:34