Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass on second click

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.

like image 610
DJ.S Avatar asked Oct 08 '15 01:10

DJ.S


3 Answers

$('.square').on('click', function() {
    var $self = $(this);
    $self.hasClass('one') ? $self.removeClass('one').addClass('two') : $self.removeClass('two').addClass('one');
});
like image 59
Mark Eriksson Avatar answered Sep 20 '22 12:09

Mark Eriksson


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>
like image 24
J Santosh Avatar answered Sep 22 '22 12:09

J Santosh


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>
like image 26
PeterKA Avatar answered Sep 19 '22 12:09

PeterKA