addClass on second click
Asked Answered
A

4

6

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.

Alluvion answered 8/10, 2015 at 1:45 Comment(1)
did you try the approach i have in mind it works and it is a bit easy to understandMarlenemarler
R
4
$('.square').on('click', function() {
    var $self = $(this);
    $self.hasClass('one') ? $self.removeClass('one').addClass('two') : $self.removeClass('two').addClass('one');
});
Runin answered 8/10, 2015 at 1:51 Comment(2)
As much as I appreciate the ternary operator, it's probably better to write it out in this case for clarity.Hecht
@J4G I agree but I wrote it for quickness as I'm on my iPhone atm, so saves me having to manually indent for each line, heheRunin
T
3

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>
Tasso answered 8/10, 2015 at 1:54 Comment(5)
You'll want to remove the old class as well, likely.Hecht
@J4G i updated my post, but i don't see anywhere in OP, that user wants to remove old class as well.Tasso
For base of concept, this is cleanest for his answer. Quick and to the point. Though, it allows him to be stuck in only a two cycle binder, where he may want to determine more. But he is probably using for a toggle. Thast would be my route, just toggle a class.Ticon
@Casey i agree with you , even toggleClass does the workTasso
But i normally don't think so deeply on these things, but this is where some answers are in a way also exceptable, but maybe not the best. The question was worde as how to determine what click count you are in. SO what if they needed to capture five events, or only 2? Toggle then wouldn't work. I think this is one of the flaws with down voting. Maybe down voting should be not able to be done by one person, but like flag it for down voting, and others in the community have to accept a down vote. Sort of how Wiki works. So people just don't down vote others, unless absolutely necessary,Ticon
W
1

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>
Welloiled answered 8/10, 2015 at 2:33 Comment(0)
T
0

Just add class 1 if first click. Then if class one exists, remove it and add class 2. If class 2 exists, remove and then start over. If you would like an example, I can write one up real quick. Example:

    $(".square").click(function(){
        var $this = $(this);
        //see where we are currently at
        if($this.hasClass("two")){
           //then we are on a third click 
        }
        else if($this.hasClass("one")){
         //we are on second click so add class
            $this.addClass("two");
        }
        else //we are on initital click
        {
            $this.addClass("one");
        }
   })

Now, I don't know what you want to do after the second click, but hopefully this gives you an idea. There are also many other ways to do this, but this is the way using your current concept.

Ticon answered 8/10, 2015 at 1:49 Comment(8)
the logic is to do this: add class 1 if no class existsl. This means it has been clicked once. In the same click event function you check if it contains class 1 or class 2. You are doing it correct, but it needs to be in the same click event, and use a logic or switch to see where you are currently at in the counter.Ticon
Typically SO answers should include some sort of code, even if it's just psuedocode. A high-level verbal representation isn't usually that helpful for someone looking for coding help.Hecht
Why the down vote, yes the above logic is the way I would go, but I was trying to explain it in a way of how he was trying to achieve it, so he would see why the logic wasn't working. But oh well. Snooty i guess. lolTicon
Well you didn't actually add code until an edit 5 minutes after your initial submission. And you didn't remove the old class either, which probably has unintended consequences.Hecht
And when they need the example, I do believe in writing the code, but I also believe in verbal explanation with their code so they understand and can extend, learn and not just copy and paste. He asked how to go about it, not to write a function that does it. What he needed to do beyond the logical checks is unknown to me. So I just displayed how based on his current thinking. But thanks for just down voting, because you know, when you have a different point of view, it is probably wrong.Ticon
"But neither works. Please help." - what do you think is more helpful on a coding website for a novice question? Telling OP "Just add class 1 if first click. Then if class one exists, remove it and add class 2. If class 2 exists, remove and then start over." doesn't tell them about hasClass, or what "starting over" might look like. Does that involve a separate event handler? Do I need to use an if statement? Don't take it personally - but your answer was too high level for the question and wasn't, IMO, a positive contribution.Hecht
Thanks @Casey! Even though this is just psuedocode, it still helped! I filled out the details on my own and it works. Also thanks everyone else who contributed. This is my first question on stackoverflow :) Looking forward to participate more or one day I can help others.Alluvion
It is a great place, and you normally do not see debating like I have been doing on this thread. I'm just tired and very talkative. He is correct though, that sudo code is not the correct way to go about answering. I just sometimes feel it is all that is needed. But welcome, to the best site for nerds. And the community is good people.Ticon

© 2022 - 2024 — McMap. All rights reserved.