Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Assigning same function to multiple values

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();
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report

0

Try:

document.addEventListener('DOMContentLoaded', function() {
    if(document.querySelector('#Button1'))
        document.querySelector('#Button1').onclick = fun;
    if(document.querySelector('#Button2'))
        document.querySelector('#Button2').onclick = fun;
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!