jQuery swapping classes is not working

Hello!
For starters I must say I haven’t used much jQuery. I just tried to swap the class of a span element between opened and closed everytime it is clicked. Can someone tell me what I am doing wrong?

        $('.opened').on('click', function() {
            alert('Closing');
            $(this).text('Open');
            $(this).removeClass('opened').addClass('closed');
        });

        $('.closed').on('click', function() {
            alert('Opening');
            $(this).text('Close');
            $(this).removeClass('closed').addClass('opened');
        });

And element is

<span class="opened">Close</span></div>

On first click it changes the class from opened to closed and alerts “Closing” but clicks after that does not change anything. The class stays at “closed” and on click keeps alerting the “Closing” like it would trigger the first block always after that.

I’d be inclined to apply a generic class to the element and use that to respond to clicks:

$('.toggle').on('click', function(){
  var isOpen = $(this).hasClass("open");
  if(isOpen){
    $(this).removeClass('open').addClass('closed');
    $(this).text('Open');
  } else {
    $(this).text('Close');
    $(this).removeClass('closed').addClass('open');         
  }
});

<span class="toggle closed">Open</span>
1 Like

Allright, I’ll give your version a go in a minute and test it out. Thanks Pullo.

In the meantime I changed the jQuery part to this and it seems to work:

$('.opened, .closed').on('click', function() {
        var elem = $(this);
	if (elem.hasClass('closed')) {
	    alert('Opening');
	    elem.removeClass('closed').addClass('opened');
	    elem.text('Close');
	} else {
	    alert('Closing');
	    elem.removeClass('opened').addClass('closed');
	    elem.text('Open');
	}
});

but if I change line

if (elem.hasClass('closed')) {

to

if (elem.hasClass('opened')) {

it does not work as expected anymore, just keeps saying “Opening” and nothing happens. What is going on here?

EDIT: Now this was a stupid user error, ofcourse if I change the condition in the if I need to swap the if and else blocks around so the logic is correct :smiley: And now that I look at it it is pretty much the same logic as in your example except I didnt use the generic class in it. I blame the FLU :smile:

Not really sure.

$('.opened, .closed').on('click', function() {

Should be the same as:

$('.opened').on('click', function() {... });
$('.closed').on('click', function() {... });

The example you gave works as expected and changed span to

<span class="toggle opened">Close</span>

Cool.
Which way round you use it is up to you : )

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.