code-8
code-8

Reputation: 58642

How can I highlight a div while on click using jQuery?

I have a bunch of divs with class tl-box

enter image description here

I want to highlight the one I clicked on.

Note: if I click on a new div, only that new div should be highlighted.


I've tried :

jQuery

$('.tl-box').click(function () {
  $(this).find('.tl-selected').removeClass('tl-selected');
  $(this).toggleClass('tl-selected');
});

CSS

.tl-selected{
    background: white;
    border:3px solid orange;
    width:179px;
    height:80px;
    position: relative;
}

Result

enter image description here

What is the best way to achieve something like this ?

Fiddle

Upvotes: 1

Views: 882

Answers (3)

Banana
Banana

Reputation: 7463

you wont find the selected box inside another box, yet you are searching it within $(this)...

simply search for it this way:

$(function() {
  $('.tl-box').click(function() {
    $('.tl-selected').removeClass('tl-selected');
    $(this).addClass('tl-selected');
  });
});
.tl-box {
  width: 100px;
  height: 50px;
  margin: 20px;
  display: inline-block;
  border: 2px solid black;
  box-sizing: border-box;
}
.tl-selected {
  background: white;
  border: 3px solid orange;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tl-box"></div>
<div class="tl-box"></div>
<div class="tl-box"></div>

Upvotes: 1

aebabis
aebabis

Reputation: 3705

In the first code snippet, this refers to the clicked item; so you won't find the previously highlighted item by searching inside it. Try replacing this:

$(this).find('.tl-selected').removeClass('tl-selected');

with this:

$('.tl-selected').removeClass('tl-selected');

Upvotes: 1

Samuel
Samuel

Reputation: 17171

Change

$('.tl-box').click(function () {
  $(this).find('.tl-selected').removeClass('tl-selected');
  $(this).toggleClass('tl-selected');
});

to

$('.tl-box').click(function () {
  $('.tl-selected').removeClass('tl-selected');
  $(this).toggleClass('tl-selected');
});

Upvotes: 1

Related Questions