user892134
user892134

Reputation: 3224

How do I use jquery to change a previous div background color?

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>

Upvotes: 0

Views: 546

Answers (4)

Cymen
Cymen

Reputation: 14419

Here is how I solved it: http://jsfiddle.net/7w2ft/. The JavaScript looks like this:

$('.select').live('click', function(event) {
    $(event.target)
        .css('background-color', 'green')        
        .prevAll('.select')
        .css('background-color', 'green');
});

Upvotes: 0

Rob W
Rob W

Reputation: 348972

Main error: id is an undefined variable. You have to add quotes around it.

Fiddle: http://jsfiddle.net/KPS7a/3/

Additional changes to get the code to work:

  • Added quotes around .attr(id) -> .attr("id")
  • Renamed var i to var id
  • Changed the inner $(".select") to $(this)
  • Changed .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 the click event, so that the color will reset on each click (previously, every tile will still be green if you first click at 5, then 1)

Upvotes: 2

Stuart Burrows
Stuart Burrows

Reputation: 10814

Also in your jsfiddle you haven't referenced jQuery. I've also made a modified version for you which I think is simpler (but requires the html you provided to be unchanged): http://jsfiddle.net/6386x/

Hope it helps!

Upvotes: 1

realshadow
realshadow

Reputation: 2585

Like Rob mentioned you need to change id to 'id' since id is undefined variable.

var i = $(this).attr('id');

You can also modify your code to something like this:

$('.select').live('click',function() {
    $(this).prevAll('div.select').css('background-color', 'green');
});

Upvotes: 0

Related Questions