-1

I have few buttons, all with same class='background'. Now I'm using this to change the background colour of button onclick.

<script>
$(document).ready(function(){
    $(".background").click(function(){
        $('.background').css('background','rgba(0,0,0,0.2)');
    });
});
</script>

But this is changing background of all the buttons. How can I change background of the button which is clicked. NOTE: I've to do this without using id

3 Answers3

2

Use this object.

$(document).ready(function(){
    $(".background").click(function(){
        $(this).css('background','rgba(0,0,0,0.2)');
    });
});
rrk
  • 15,677
  • 4
  • 29
  • 45
2

Use context this in clicked event to only target currently clicked element:

$(".background").click(function(){
    $(this).css('background','rgba(0,0,0,0.2)');
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

Hope this will help

$(document).ready(function(){
    $(".background").click(function(){
        $(".background").css('background',''); // Reset background color of other buttons
        $(this).css('background','rgba(0,0,0,0.2)'); // Set backgroundcolor of this button
    });
});

jsfiddle

brk
  • 48,835
  • 10
  • 56
  • 78