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
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:
As others have mentioned, fire the
click
event after theDOMContentLoaded
event.Here is a reusable function for triggering a click event for a given selector: