Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Event Listener does not work

´´´html <button class = corner-add>Corner Add</button> ´´´

I want that button to turn a lighter shade of green when you mouseover it, so I used the following code:

´´´javascript buttons[4].addEventListener('mouseover', () => { buttons[4].style.backgroundColor = '#21897E'; });

  buttons[4].addEventListener('mouseout', () => {
    buttons[4].style.backgroundColor = '#2E9763';
  });

´´´ This is the fifth button in the array, so it should work. But it does not work, why is this?

eslam said
eslam said
Courses Plus Student 6,734 Points

please give us your full html code and Wrap your code with 3 backticks (```) on the line before and after

There you go, I updated the code

eslam said
eslam said
Courses Plus Student 6,734 Points

Still your code is so messy cant read it but anyway if this is your full html if you just have 1 button why you selected it like that buttons[4] ?

i will assume that you just have a single button tag in your element so you will select it like that

Html

    <button class="coner-add"><Corner Add</button>

Javascritpt

// you can use query selector to directly select the first button tag in your page

    let button = document.querySelector('button');

// you can use query selector to select a button with a specific class

    let button = document.querySelector('button.corner-add');

// you can use .getElementsByClassName ( This method will return a node list with zero index )

    let button = document.getElementsByClassName('corner-add')[0];

Add Event Listener

   button.addEventListener('mouseover ', () => {

   button.style.backgroundColor = '#2E9763';

})

1 Answer

Steven Parker
Steven Parker
229,732 Points

I suspect the problem is where you establish the value for "buttons", that part of the code is not shown here.

Otherwise, the code that is shown here should work.

Another possibility might be if you're using some additional CSS (including a front-end framework) that is interfering with these settings.