javascriptmicrosoft-edge

JavaScript click() method not working on Microsoft Edge


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)


Solution

  • 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();
        }
    });