What I’m trying to do is, if a div is clicked on, that div and its predecessors have the same background color. For example if ‘4’ is clicked on; 4, 3, 2 and 1 have the same background color. I tried unsuccessfully to achieve this, how do I fix it?
http://jsfiddle.net/mdanz/KPS7a/
<style type="text/css">
.selectcontainer {
overflow:hidden;
display:block;
}
.select {
display:block
width:50px;
height:40px;
background-color:#59758d;
text-align:center;
font-family:arial;
font-weight:bold;
color:#FFFFFF;
font-size:24px;
cursor:pointer;
padding-top:10px;
}
.select:hover {
border:1px solid #d99c29;
font-size:32px;
}
</style>
<script type"text/javascript">
$(function() {
$('.select').live('click',function() {
var i = $(this).attr('id');
$('.select').each(function(i){
$('.select').css({'background-color':'green'});
});
});
});
</script>
<div class='selectcontainer'>
<div class='select' id='1'>1</div>
<div class='select' id='2'>2</div>
<div class='select' id='3'>3</div>
<div class='select' id='4'>4</div>
<div class='select' id='5'>5</div>
<div class='select' id='6'>6</div>
</div>
Main error:
idis an undefined variable. You have to add quotes around it.Fiddle: http://jsfiddle.net/KPS7a/3/
Additional changes to get the code to work:
.attr(id)->.attr("id")var itovar id$(".select")to$(this).css("background-color", "green")to.addClass("green")Added a new declaration to the CSS:
.green { background-color: green}Added
$(".green").removeClass("green")at the beginning of theclickevent, so that the color will reset on each click (previously, every tile will still be green if you first click at 5, then 1)