Reputation: 41
I have an element that once you click on it, it adds and removes a class with jQuery. When you click on a child element I want the classes to swap again.
I tried doing it with .parent
but that doesn't seem to work..
This is the html:
<article class="block inactive">
<span class="close"></span>
</article>
And jQuery:
$('.block').click(function(){
$(this).removeClass('inactive'),
$(this).addClass('active');
});
$('.close').click(function(){
$(this).parent().addClass('inactive');
$(this).parent().removeClass('active');
});
EDIT
Solution:
$('.block').click(function(){
$(this).addClass('active');
$(this).removeClass('inactive');
});
$('.close').click(function(e){
$(this).parent('.block').toggleClass('inactive active');
e.stopPropagation();
});
Upvotes: 1
Views: 6002
Reputation: 136094
Because the .close
is a child of the .block
the event is propagating back up and also triggering the handler oon the .block
, which means that the classes are getting reverted straight away. You can use .stopPropagation()
to stop this happening:
$('.block').click(function(){
$(this).removeClass('inactive'),
$(this).addClass('active');
});
$('.close').click(function(e){
$(this).parent().addClass('inactive');
$(this).parent().removeClass('active');
e.stopPropagation();
});
.inactive{ background-color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article class="block inactive">
in the block
<span class="close">in the close</span>
</article>
There are a number of other enhancements you can make to simplify your code, but they are tangential to the question, for completeness
toggleClass
is more appropriate than addClass
/removeClass
.$('.block').click(function(){
$(this).removeClass('inactive').addClass('active');
});
$('.close').click(function(e){
$(this).parent().addClass('inactive').removeClass('active');
e.stopPropagation();
});
.inactive{ background-color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article class="block inactive">
in the block
<span class="close">in the close</span>
</article>
Upvotes: 8