0

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/ .

3 Answers 3

2

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>

Sign up to request clarification or add additional context in comments.

4 Comments

@user3858546 , It works like this. +1, good answer!;)
YEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!!! THANKS!
@user3858546 Exclamation of happiness and excitement? ;)
@user3858546 YAY Happy to help you :)
1

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;   
}

Comments

1

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 }

2 Comments

I just removed jquery. No jquery for this.
Okay. Then you can still use the getElementById stuff but set up your function the way I described at the bottom. That should make sure it all doesn't change at once

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.