user3858546
user3858546

Reputation: 83

Change CSS On Hover

I try to make each of them separated.

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This will change b element</div>
<div id="b">This is element b</div>

<div id="f" onmouseover="chbg('blue')" onmouseout="chbg('white')">This will change g element</div>
<div id="g">This is element g</div>

<div id="j" onmouseover="chbg('yellow')" onmouseout="chbg('white')">This will change k element</div>
<div id="k">This is element k</div>

Here is JS

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
    document.getElementById('g').style.backgroundColor = color;    
    document.getElementById('k').style.backgroundColor = color;    
}

Doesn't work properly here http://jsfiddle.net/qUzn5/ .

Upvotes: 0

Views: 842

Answers (3)

magnified
magnified

Reputation: 78

You tagged this with jQuery so I'm going to assume you're using that. If so, cut down your code a bit like this...

$('#b').css('background-color', color);

If you're using jquery you shouldn't need to use getElementById and .style.

http://api.jquery.com/css/#css2

And since your function has everything in it, each background will change.

If you must use javascript instead of CSS, try passing a different argument to your function. Perhaps the ID of the background that should change. Then set conditionals in your function according to what ID is passed.

if ( divId == 'b ) { Code to change b div }

Upvotes: 1

Oliver-H-Miller
Oliver-H-Miller

Reputation: 451

You might want to put a second argument in your function like this:

JavaScript:
function chbg(color, id) { document.getElementById(id).style.backgroundColor = color;
}



HTML:
(Repeat the div's)

<div id="a" onmouseover="chbg('red', 'a')" onmouseout="chbg('white')">This will change b element</div>

Upvotes: 2

PSZ_Code
PSZ_Code

Reputation: 1045

Currently they all get colored because the function calls each of the ids

I guess you should add a variable to your javascript function. This variable contains the id of the element to be changed.

I do not know anything of javascript, but i guess it should look like this:

function chbg(id,color) {
document.getElementById(id).style.backgroundColor = color;   
}

Upvotes: 1

Related Questions