Javascript – Trigger OnClick only once if QueryString present

I am looking to trigger an OnClick event, only once, if a querystring is present in the URL.

Ex:

var QueryString = window.location.search;
if (QueryString) {
  document.getElementById("abc").click();
}
<a href="" onclick="alert('clicked')" id="abc">click this</a>

Which this code, if there is a querystring present, it does fire the OnClick event, but seems to repeat the cycle (after I click OK on the alert, in this case). I’m looking to fire the OnClick event only once.

Thank you!

Answer

The problem

Programmatically clicking the <a> tag creates a navigation loop:

  1. href="" is not the absence of a link and uses window.location as the link address.
  2. window.location contains a query string.
  3. A query string in a URL being navigated to generally requires the browser to reload the page from the server without using cached copies.
  4. Both the first page load and reloading it executes the script code.
  5. The script code issues an alert, and after being dismissed, clicks the link element. This navigates to a URL with a query string.
  6. Navigation repeats from step 3.

Solutions

Ways to solve the issue could include

  • Provide a document fragment identifier in the href value, e.g. href="#", in the link address. By design this prevents page reload during navigation even if location.search is non-empty. It will, however, navigate to the fragment identifier provided.

  • Set window.location.search to the empty string before programatically clicking the anchor element. Although untested it is also so unusual that I wouldn’t recommend doing so.

  • Don’t use an anchor tag for the clicked element (which can prevents unwanted scrolling effects), or

  • Call event.preventDefault in the click event handler. As an untested example:

     <a href="" onclick="event=>{event.preventDefault(); alert("hi")}">click me"</a>
    

    (disclaimer: addition of the event handler in this manner if for demonstration and is not “how to add an event handler for ongoing code use”.)