Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript event listening

Please tell me why when I click on the ones "1111111111" in the browser, the function is called, and when I click on the twos "2222222222", the function is not called, please explain why and how to fix it?

const contactButton = document.querySelector('.contact-button');

contactButton.addEventListener('click', () => {
  console.log('Hello')
})
<div class="contact-button">1111111111</div>
<div class="contact-button">2222222222</div>

I will be grateful for help. Thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The reason the click event is not being triggered for the second "2222222222" element is due to the way you are selecting the .contact-button elements and adding event listeners to them.

Here’s how you can modify your JavaScript code:

const contactButtons = document.querySelectorAll('.contact-button');
            
contactButtons.forEach(button => {
    button.addEventListener('click', () => {
        console.log('Hello');
    });
});

With this change, the event listener will be added to all elements with the class contact-button, and clicking any of them will log "Hello" to the console.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading