2

I need to change hover backgroundColor in Javascript

function changeColor(color) {
var block = document.getElementsByClassName('kafelek');
for (var i = 0; i < block.length; i++) {
    block[i].style.backgroundColor = "#" + color;
}};

In this code, I change color of block after click, but i need to change color of block after hover too.

<div class="kolorek" onclick="changeColor('2ecc71');" style="background-color:#2ecc71;"></div>
5
  • developer.mozilla.org/en-US/docs/Web/Events Commented Dec 23, 2016 at 16:14
  • This code just changes the background color. When this code runs is related to how you attach this to the event. Show us the code you use to bind this to the event of some element. In general for hover check out the mouseover and mouseout events Commented Dec 23, 2016 at 16:14
  • In addition to the above comments, are you aware that background-color can be changed on hover with CSS and no JavaScript? Commented Dec 23, 2016 at 16:15
  • <element onmouseover=""> Commented Dec 23, 2016 at 16:16
  • I have paletee of colors, and while im clicking one of them all blocks in other class are changing colors. Commented Dec 23, 2016 at 16:26

1 Answer 1

2

Maybe try the mouseleave event:

element.addEventListener("mouseleave", function( event ) {   
    event.target.style.backgroundColor = "purple";
}

Also if you want it to change only when the mouse is on the element, you better use css :hover, like so:

element:hover {
    background-color: #yourcolor;
}
Sign up to request clarification or add additional context in comments.

1 Comment

But i need to dynamic change this color, so i have to use javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.