JQuery: How to create addClass and removeClass loop

Hello all!

I need a little help here. I created a header that has bars icon, when ever you click it the icon changes to X.

I simply created a JS code that when ever the user clicks the icon changes to X, then click and it changes back to bars.

Now the code works, but the X doesn’t go back to bars again…so I need help with that if you may?


jQuery(document).ready(function() {
	jQuery('.bars').click(function() {
		jQuery('#nav_menu').toggle();
		jQuery('.fa').removeClass("fa-bars");
		jQuery('.fa').addClass("fa-times");
	});
});

We would need to see a sample page that demonstrates the problem, to most effectively come up with a solution for you.

1 Like

Hello,

here you go:

1 Like

Thanks, that helped to confirm my suspicions.

Your addClass/removeClass code is effective for showing the times, but you need the opposite of those to hide the times.

I recommend that you replace addClass and removeClass with toggleClass instead.

1 Like

Thank you!!

here is what I did:

jQuery(document).ready(function() {
	jQuery('.bars').click(function() {
		jQuery('#nav_menu').toggle();
		jQuery('.bars > .fa').toggleClass('fa-bars fa-times');
	});
});

and it’s working

3 Likes

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