ohhConti
ohhConti

Reputation: 71

Change background-color of button with JavaScript

I'm writing a HTML webPage, I use a button and I need to change his background-color on mouseover using a javascript function. Here is the code.

<button onmouseover="funzione(this)">BTN</button>
<script>
    funzione(x){
        x.style.background-color=#ffffff;
    }
</script>

Upvotes: 0

Views: 631

Answers (5)

Irfan Pathan
Irfan Pathan

Reputation: 325

You can do this simply in CSS, its easy, efficient and less code.

<style type="text/css">
.myHoverButton:hover { background-color: #ffffff; }
</style>

<button id="button1" class="myHoverButton">

Upvotes: 0

sumit chauhan
sumit chauhan

Reputation: 1300

function funzione(x){
  x.style.backgroundColor = "#ffffff";
}
<button onmouseover = "funzione(this)">BTN</button>

Upvotes: 0

kcode
kcode

Reputation: 402

If you want in js:

<button onmouseover="set_color(this)">BTN</button>
<script>
function set_color(x){
	x.style.backgroundColor='red';
}
</script>

Upvotes: 0

Adam Azad
Adam Azad

Reputation: 11297

This is very basic. You're missing keyword function, and with that style of accessing properties, you need to use camel case. Finally, wrap the color hex within quotes.

function funzione(x){
   x.style.backgroundColor= '#ffffff';
}
<button onmouseover="funzione(this)">BTN</button>

The recommended way is use CSS in production, but if you're just into JavaScript and want to explore, it's fine.

Upvotes: 0

Arkadiusz Wieczorek
Arkadiusz Wieczorek

Reputation: 451

In JavaScript you need get handler to element x e.g.:

var x = document.getElementById("x");

but you should do this with CCS:

button{
    background-color: yellow;
}

button:hover{
    background-color: lime;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/:hover

Upvotes: 1

Related Questions