1

I'm looking to use jQuery to change the background color of a div on click (which I've got working!) However one click changes all of the divs color at that point, I'm wondering if there is any way to change the color for the specific element that has been clicked without affecting the others?

$(document).ready(function() {
  $(".bg").click(function() {
    $(".bg").css("background-color", "red");
  });
});
.bg {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="bg">
  <p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<div class="bg">
  <p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<div class="bg">
  <p id="demo" onclick="colorSwitch()">Click me to change my text color.</p>
</div>
<p>A function is triggered when the div element is clicked. The function sets the background-color of the div element to red.</p>

Also JSFiddle is here: https://jsfiddle.net/davywest1000/jd82hq5t/2/

Thanks in advance!

1 Answer 1

4

You have just to use $(this) keyword to refer to the clicked element.

NOTE: Remove the inline event onclick="colorSwitch()" since you have already attached the event in your JS code and if you want to call the function colorSwitch you could call it inside the event.

$(document).ready(function() {
  $(".bg").click(function() {
    $(this).css("background-color", "red");
  });
});
.bg {
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="bg">
  <p id="demo">Click me to change my text color.</p>
</div>

<div class="bg">
  <p id="demo">Click me to change my text color.</p>
</div>

<div class="bg">
  <p id="demo">Click me to change my text color.</p>
</div>

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

1 Comment

Ahh excellent I'd been trying 'this' but mustn't have found the correct location! Thank you very much!!!!

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.