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

Gabriel Caraos
Gabriel Caraos
4,358 Points

How to change the background color as you hover over the boxes using pure javascript.

I created 4 boxes with different color. I was planning to change the background to white and add a border of its background color as you hover into the box.

Here is how it looks in codepen. https://codepen.io/anon/pen/mjoBVL

you have mouse over evend listener .

https://www.w3schools.com/jsref/event_onmouseover.asp

and you can use if else statement good luck!!

2 Answers

I think this would work if it's what your going for:

const box = document.querySelectorAll(".box")

box.forEach(function(myBox) {
  const color = window.getComputedStyle(myBox).getPropertyValue('background-color'); //grabs the css background color
  myBox.addEventListener('mouseover', function(e) {

    e.target.style.backgroundColor = 'white';
    e.target.style.border = `1px solid ${color}`;
  });
  myBox.addEventListener('mouseleave', function(e) {
    e.target.style.backgroundColor = color;
    e.target.style.border = '1px solid white'; //could do this so adding the border doesnt jump the box 
  });
});

Adding the border jumps the box around but i think this should do what you want.

Gabriel Caraos
Gabriel Caraos
4,358 Points

Yes, this is what I was going for. Thanks for the help!

For the thunder-cloud box:

document.getElementById("thunder-cloud").addEventListener("mouseenter", function(){
    document.getElementById("thunder-cloud").style.backgroundColor = "white";
    document.getElementById("thunder-cloud").style.border = "thick solid #505260"; 

});

document.getElementById("thunder-cloud").addEventListener("mouseleave", function(){
    document.getElementById("thunder-cloud").style.backgroundColor = "#505260";
   document.getElementById("thunder-cloud").style.border = "none";
});