1

I have two or more divs with the first being selected. When I click the other div, that div becomes selected. I'm doing this with a background color.

CSS:

.red {background: red}

HTML:

<div class="foo">...</div>
<div class="foo">...</div>
<div class="foo">...</div>

JavaScript:

$('.foo').click(function(){
 //$(this).toggleClass('red') Not ideal as the active div must always be red
 // If selected, remove all red classes then add class?
});

Since it's an event click, I'm not sure how to remove all other classes with red and add red class to the clicked div.

In short, "highlight" div when selected and if page is refreshed, the first div should have a background of red as that's the selected div.

Sylar
  • 11,422
  • 25
  • 93
  • 166
  • It's better to use a class name that indicates why something looks the way it does, not how it looks. Here you could use `highlight`. `.highlight { background: blue; }` makes more sense than `.red { background: blue; }`. – Arjan Nov 20 '16 at 06:42
  • @Arjan I'm rubbish with names but that's what I'm working on. In short, I only want to give the selected div a background color. If clicked twice, the background color does not change. On deeper research, this question is a duplicate of http://stackoverflow.com/questions/30810821/highlight-div-onclick Many thanks for the supported questions and I could use them in other projects. – Sylar Nov 20 '16 at 06:46

3 Answers3

1

You want like this?

$("#root").bind("click",function(e){
    $("#root").find(".foo").removeClass("red");
    $(e.target).addClass("red");
})
.red {background: red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="root">
  <div class="foo red">...</div>
  <div class="foo">...</div>
  <div class="foo">...</div>
</div>
Ying Yi
  • 784
  • 4
  • 16
0

Using siblings() method get sibling elements and remove red class from them.

$('.foo').click(function() {
  $(this).addClass('red') // add class to clicked element
    .siblings() // get siblings
    .removeClass('red'); // remove class from sibling elements 
});

$('.foo').click(function() {
  $(this).toggleClass('red')
    .siblings().removeClass('red')
});
.red {
  background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">...</div>
<div class="foo">...</div>
<div class="foo">...</div>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • I'd rather not to use `toggleClass` as it removes the class. But this works when used `addClass`. You see, If I click the same div twice, the class adds and removes with toggle. – Sylar Nov 20 '16 at 06:43
  • 1
    @Sylar : If you don't want to toggle then use `addClass` – Pranav C Balan Nov 20 '16 at 06:46
0

Here are the JS you want

$('.sample').click(function() {
  $(this).addClass('addColor')
    .siblings().removeClass('addColor')
});

See this fiddle

ONE_FE
  • 968
  • 3
  • 19
  • 39