Reputation: 58642
I have a bunch of divs with class tl-box
I want to highlight the one I clicked on.
Note: if I click on a new div, only that new div should be highlighted.
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
What is the best way to achieve something like this ?
Upvotes: 1
Views: 882
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
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
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