skip to Main Content

I’ve been trying to fire a click event on page load with the code below

window.onload = function () {
  var click = document.querySelector('li[data-filter=".architecture"]');
  console.log(click)
  if (click) {
    click.click()
  }
}
<li data-filter=".architecture" onclick="alert('clicked')">Item</li>

In chrome the above code works just fine, although in microsoft edge the click() method does not seem to work for some reason.
Doing console.log it displays the element in all the browsers i have tried (including microsoft edge) and they do not display any errors.

Microsoft Edge Version: 124.0.2478.67 (Official build) (64-bit)

2

Answers


  1. window.onload event waits for the entire page, including its stylesheets, images, subframes, and other assets to load completely before executing your JavaScript code and that could result in a couple of issues like the one you mention. Latency could also be a factor.

    You might want to try a more modern approach such as DOMContentLoaded

    Here is a revision to your code that might do the trick for you:

    document.addEventListener('DOMContentLoaded', function () {
        var click = document.querySelector('li[data-filter=".architecture"]');
        
        if (click) {
            click.click();
        }
    });
    
    Login or Signup to reply.
  2. As others have mentioned, fire the click event after the DOMContentLoaded event.

    Here is a reusable function for triggering a click event for a given selector:

    document.addEventListener('DOMContentLoaded', function() {
      triggerClick('li[data-filter=".architecture"]');
    });
    
    function triggerClick(selector) {
      document.querySelector(selector)
        ?.dispatchEvent(new MouseEvent('click', {
          view: window,
          bubbles: true,
          cancelable: true
        }));
    }
    <li data-filter=".architecture" onclick="console.log('clicked')">Item</li>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search