Back to all resources
URL hash
click event
web development

Programmatically Click Element Based on URL

By Corey Moen
This JavaScript code snippet is designed to check the current URL of the webpage for a specific hash value. If the URL contains the hash "#example", the script triggers a click event on an HTML element with the ID "example". This is typically used to programmatically simulate a user clicking on a specific element when the page is loaded with a certain hash in the URL.

The code operates as follows:
  1. It checks if the current URL's hash (the part of the URL following the '#' symbol) matches "#example".
  2. If a match is found, it retrieves the HTML element with the ID "example" using document.getElementById("example").
  3. It then triggers a click event on that element using the .click() method.
This functionality is useful for automatically triggering actions on page load based on URL fragments, which can enhance user navigation and interaction within single-page applications or when using anchor links for navigation.