I have some code working, that toggles the class "active" on and off when you click on a swatch-wrapper div.
However I would only like one of these div's to have the active class at a time. Right now I could click them all, and they would all have the active class. I'm not sure how to remove the class from all the other div's except for the one I just clicked on.
I tried to use .parent(), but it didn't seem to work / I don't think I was using it correctly.
HTML
<div class="variation_form_section">
<div class="select">
<div class="swatch-wrapper"></div>
<div class="swatch-wrapper"></div>
<div class="swatch-wrapper"></div>
</div>
</div>
JS
<script>
$(document).ready(function(){
$(".variation_form_section .select div").each(function() {
$(this).click(function() {
if($(this).hasClass( "active" )){
$(this).removeClass( "active" );
}else{
$(this).addClass( "active" );
}
});
});
});
</script>
To remove all CSS classes of an element, we use removeClass() method. The removeClass() method is used to remove one or more class names from the selected element.
The removeClass() method removes one or more class names from the selected elements. Note: If no parameter is specified, this method will remove ALL class names from the selected elements.
removeClass() Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
To remove elements and content, there are mainly two jQuery methods: remove() - Removes the selected element (and its child elements) empty() - Removes the child elements from the selected element.
You can use not like this:
$(".variation_form_section .select div").click(function() {
$(".variation_form_section .select div").not($(this)).removeClass('active');
});
Simply, remove active
class from them all and then add active
class to the clicked element.
$(document).ready(function(){
$(".variation_form_section .select div").click(function() {
$('.variation_form_section .select div').removeClass('active');
$(this).addClass('active');
});
});
Demo: http://jsfiddle.net/conm54k2/
You can try with .siblings() http://api.jquery.com/siblings/
$(document).on('ready', function(){
$(".variation_form_section .select div").on('click', function() {
$(this).addClass('active').siblings().removeClass('active');
});
});
demo: http://jsfiddle.net/conm54k2/4/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With