Frage

I'm trying to toggle a class on a single button, where the class would be dynamically assigned based on a state. Here is my code:

$('body').on('click', '.button', function () {
    var $itm = $(this).children(".icon");
    if ($itm.hasClass('hide')) {
        $itm.toggleClass('unhide', 'hide')
    } else {
        $itm.toggleClass('hide', 'unhide')
    }
});

What I'm trying to achieve is this: If a button has class .hide, the onclick toggles this class to .unhide, and vice versa.

So far the only time class toggling works is, is on the second click. The first click does not change anything.

War es hilfreich?

Lösung

.toggleClass accepts one or more class names separated by a space like this:

$('body').on('click', '.button', function () {
    $(this).children(".icon").toggleClass("hide unhide");
});

Working example (with a tweak to your HTML): http://jsfiddle.net/jfriend00/9tV33/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top