Laurence L Laurence L - 6 months ago 19
Javascript Question

toggle class and visibility, display

If I also want to toggle the display block: none.

How do I do this

$('.exp').on('click', function() {
"use strict";
$(this).toggleClass("plus_sign minus_sign");
$(this).toggleClass("plus01 minus01");
});


The plus_sign and minus sign classes each have an image to indicate the plus and the minus. As the classes toggle, if the class is minus_sign I want the minus image to show. If the class is plus_sign I want the plus image to show and the minus image to hide. The images are background images in the CSS.

Thanks

Answer

You're making it too difficult.

First, set all .exp elements to use the plus sign (if the default is to show the plus). Then toggle a class that switches the class so the minus is show. Here's some quick code, which should get you there...

$('.exp').on('click', function() {
    $(this).toggleClass('hide_plus');
});

Your CSS will be something like this:

.exp {
    background:url(/path/to/plus.gif);
}
.hide_plus {
    background:url(/path/to/minus.gif);
}

BTW, you're better off using a sprite for these icons and then shifting the position of the background image. Or use something like fontawesome.

Here's a rough fiddle with the +/- toggling without images. Adding the images shouldn't be too difficult.

https://jsfiddle.net/tycahill/1pwbuvga/