Reputation: 189
I want to include this code multiple times in the same page using php (include).
html code:
<div class="red" onclick="red()">red</div>
<div class="green" onclick="green()">green</div>
<div class="blue" onclick="blue()">blue</div>
<div id="change">click on the colors to change the div color</div>
css code:
.red{background-color: red;width: 50px;}
.green{background-color: green;width: 50px;}
.blue{background-color: blue;width: 50px;}
#change{background-color: yellow;width: 100px;}
javascript code:
function red()
{
document.getElementById('change').style.background="red";
}
function green()
{
document.getElementById('change').style.background="green";
}
function blue()
{
document.getElementById('change').style.background="blue";
}
This code works fine in the first div (id=change) but in the second div when I click on the div with class=red it changes the first div instead of the second.
How can I make it change the div that is below it?
problem solved:
http://jsfiddle.net/wjp4pqw6/1/
Upvotes: 0
Views: 177
Reputation: 368
Try this,
HTML
<div>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<div class="change">click on the colors to change the div color</div>
</div>
<div>
<div class="red">red</div>
<div class="green">green</div>
<div class="blue">blue</div>
<div class="change">click on the colors to change the div color</div>
</div>
CSS
.red{background-color: red;width: 50px;}
.green{background-color: green;width: 50px;}
.blue{background-color: blue;width: 50px;}
.change{background-color: yellow;width: 100px;}
JS
$(function() {
var colors = ["red", "green", "blue"];
$.each(colors, function() {
var color = this;
$("." + color).click(function() {
$(this).siblings(".change").css("background", color)
});
});
});
Upvotes: 0
Reputation: 599
I have written some code that should do it for you:
PHP
for($i=0; $i<10; $i++) {
echo '<div id="containter_'.$i.'">';
echo '<div class="red" onclick="color(\'red\', this);" id="red_'.$i.'">red</div>';
echo '<div class="green" id="green_'.$i.'" onclick="color(\'green\', this)">green</div>';
echo '<div class="blue" id="blue_'.$i.'" onclick="color(\'blue\', this)">blue</div>';
echo '<div class="change" id="change_'.$i.'"></div>';
echo '</div>';
}
That echo's 10 blocks of your code.
Javascript
function color(c, elem) {
id = elem.id.replace(c,'');
document.getElementById('change'+id).style.background=c;
}
CSS
.red{background-color: red;width: 50px;}
.green{background-color: green;width: 50px;}
.blue{background-color: blue;width: 50px;}
.change{background-color: yellow;width: 100px;}
Hope this helps.
Upvotes: 1