The #Button1 works when I click it but #Button2 does not. If I change the order of them then 2 works but 1 doesn't. Can you not set the same function to multiple events? How would I make this work. Both buttons are on different html pages if that makes a difference.
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#Button1').onclick = fun;
document.querySelector('#Button2').onclick = fun;
});
function fun() {
alert();
}
You are trying to attach an event to something that does not exist. So of course it will throw an error. Looking at the developer console you would see an error message. VM1455:1 Uncaught TypeError: Cannot set properties of null (setting 'onclick')
If only one element exist you can make one selector that targets both
document.querySelector('#Button1, #Button2').addEventListener("click", fun);
or use a common class on the buttons
document.querySelector('.myFunButton').addEventListener("click", fun);
Or you can check to see if the element exists.
document.querySelector('#Button1')?.addEventListener('click', fun);
document.querySelector('#Button2')?.addEventListener('click', fun);
Try:
document.addEventListener('DOMContentLoaded', function() {
if(document.querySelector('#Button1'))
document.querySelector('#Button1').onclick = fun;
if(document.querySelector('#Button2'))
document.querySelector('#Button2').onclick = fun;
});