Reputation: 243
I am make a list and in the list when I click it toggles class active
but previous elements still contains active
class when I click on different element
<ul>
<li class="click_me">Here </li>
<li class="click_me">Here </li>
<li class="click_me">Here </li>
<li class="click_me">Here </li>
</ul>
$(document).ready(function()
{
$('.click_me').click(function()
{
$.each(function()
{
$('.click_me').toggleClass('active');
});
$(this).toggleClass('active');
});
});
<style>
.active
{
background-color: red;
}
</style>
What I want is that when I click on different li
element previous li
's active
class must be toggled out. Sorry for poor english!
I tried to add each loop but it didn't work.
Upvotes: 0
Views: 2362
Reputation: 130145
$('ul').on('click', '.click_me', function(){
$(this).toggleClass('active').siblings().removeClass('active'); // <--- The trick!
})
.active{ background:lightblue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="click_me active">Click here</li>
<li class="click_me">Click here</li>
<li class="click_me">Click here</li>
<li class="click_me">Click here</li>
</ul>
That should do it!
Upvotes: 3
Reputation: 2817
Try this. It should work! All answers work!
$('.click_me').click(function()
{
$('.click_me.active').removeClass('active');
$(this).addClass('active');
});
Upvotes: 2
Reputation: 9794
Try this.
Remove the class from all the li elements excluding the clicked element and toggle class on clicked element.
$(document).ready(function()
{
$('.click_me').click(function()
{
$("li.active").not(this).removeClass('active');
$(this).toggleClass("active");
});
});
.active
{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="click_me">Here </li>
<li class="click_me">Here </li>
<li class="click_me">Here </li>
<li class="click_me">Here </li>
</ul>
Upvotes: 2
Reputation: 337560
To get this to work you simply need to remove the .active
class from any elements that already have it, excluding the current element, which should be toggled. Try this:
$('.click_me').click(function() {
$('.active').not(this).removeClass('active');
$(this).toggleClass('active');
});
.active {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="click_me">Here</li>
<li class="click_me">Here</li>
<li class="click_me">Here</li>
<li class="click_me">Here</li>
</ul>
Upvotes: 4
Reputation: 31692
$('.click_me').click(function()
{
// remove the .active class from all the .active elements.
$('.click_me.active').removeClass('active');
// add it to this one
$(this).addClass('active');
});
Upvotes: 1