1

I am working around a simple jQuery script that is changing the backgroud color of an element when clicked.

Here is my code:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>

<div class="radio">Text1</div>
<div class="radio">Text2</div>
<div class="radio">Text3</div>
<div class="radio">Text4</div>

I want the following to happen:

I click on "Text1" and this div is changing his background color to red and stay red.

I click on "Text2" and the background color of "Text1" is going back to white and then the background color of "Text2" is going and stay red.

I hope i give you a good description.

Can you help me make it ?

Thanks in advance!

2 Answers 2

1

$('.radio').click(function(){
  $('.red').removeClass('red');
  $(this).addClass('red');
});
.red{
background-color: red; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div class="radio">Text1</div>
<div class="radio">Text2</div>
<div class="radio">Text3</div>
<div class="radio">Text4</div>

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

Comments

0

Here is a way to do it with pure CSS:

input {
  display: none;
}
label {
  display: block;
}
input:checked + label {
  background-color: red;
}
<input id="text1" type="radio" name="g1">
<label for="text1">Text1</label>
<input id="text2" type="radio" name="g1">
<label for="text2">Text2</label>
<input id="text3" type="radio" name="g1">
<label for="text3">Text3</label>
<input id="text4" type="radio" name="g1">
<label for="text4">Text4</label>

Comments

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.