This is the behavior I have in mind:
Say you have one square. <div class="square"></div>
On the first click, add class "one":
$(".square").click(function(){
addClass("one");
})
and it works.
Then on second click, add class "two". Not sure how to make that happen. I've tried below:
$(".square.one").click(function(){
$(".square.one").addClass("two");
});
and
$(".square").hasClass("one").click(function(){
this.addClass("two");
})
But neither works. Please help.
$('.square').on('click', function() {
var $self = $(this);
$self.hasClass('one') ? $self.removeClass('one').addClass('two') : $self.removeClass('two').addClass('one');
});
try this
$(".square").click(function () {
if ($(this).hasClass('one')==true)
{
$(this).addClass("two");
$(this).removeClass("one");
}
else
$(this).addClass("one")
})
$(".square").click(function() {
if ($(this).hasClass('one') == true) $(this).addClass("two");
else $(this).addClass("one")
})
.one {
color: #00f;
}
.two {
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='square'>fooo bar</div>
You can use the jQuery .filter()
method to first check if the element clicked has the class .one
, if so, add .two
if not continue.
$('.square').on('click', function() {
$(this).filter('.one').addClass('two').end().addClass('one');
});
$('.square').on('click', function() {
//show classes
console.log( this.className );
$(this).filter('.one').addClass('two')
.end().addClass('one');
});
.square {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
Another approach would be to use event delegation, considering $('.square.one')
appears like an element added after DOM ready, but you don't want to go that high up in the DOM tree as that may cost you. So you may use the parent of the target element instead of document
:
$('.square').on('click', function() {
$(this).addClass('one');
})
.parent().on('click', '.one', function() {
$(this).addClass('two');
});
$('.square').on('click', function() {
$(this).addClass('one');
//show classes
console.log( this.className );
})
.parent().on('click', '.one', function() {
$(this).addClass('two');
});
.square {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="square"></div>
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