-5

How can I on click add and remove a class with jQuery? I need .other-class to be unaffected.

So when you click .other-class.one it becomes .other-class.two. If you click on .other-class.two it becomes .other-class.one.

This is what I have so far however the 2nd load of JS doenst work.

<p class="other-class one">Trigger</p>
.one {
  background: red;
}
.two {
  background: blue;
}
.other-class {
    text-decoration: underline;
}
$('.one').click(function(){
    $(this).removeClass('one');
    $(this).addClass('two');
});

$('.two').click(function(){
    $(this).removeClass('two');
    $(this).addClass('one');
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Evanss
  • 23,390
  • 94
  • 282
  • 505
  • Why has this question got so many downvotes? – musefan Dec 02 '14 at 11:04
  • I would say the only bad thing about this question, is that the OP doesn't explicitly mention what it is about the 2nd load of JS that doesn't work. What exactly happens that shouldn't happen? – musefan Dec 02 '14 at 11:11

4 Answers4

5

You need to use event delegation:

$('body').on('click','.one',function(){
 $(this).removeClass('one').addClass('two');
});

$('body').on('click','.two',function(){
 $(this).removeClass('two').addClass('one');
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
2

In this case you can use toggleClass(), but as a normal solution to this kind of dynamic selector scenario you should use event delegation

$('.one, .two').click(function() {
  $(this).toggleClass('one two');
});
.one {
  background: red;
}
.two {
  background: blue;
}
.other-class {
  text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="other-class one">Trigger</p>

Why? Because in the normal event delegation model the selector is evaluated only once when the registration code is executed so in your example only the first handler is added to the p element so how many times you click only the first handler is executed

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2
$(body).on('click', '.other-class' function() {
    $(this).toggleClass('one two');
});
kapantzak
  • 11,610
  • 4
  • 39
  • 61
0

I assume you are looking for a toggle effect. You could just assign the event to the "common" class, and then toggle. Like so:

$('.other-class').click(function(){
    if($(this).hasClass('one'))
        $(this).removeClass('one').addClass('two');
    else
        $(this).removeClass('two').addClass('one');
});

Here is a working example

musefan
  • 47,875
  • 21
  • 135
  • 185