jQuery toggle CSS?

jQuery toggle CSS?

For jQuery versions lower than 1.9 (see https://api.jquery.com/toggle-event):

$(#user_button).toggle(function () {
    $(#user_button).css({borderBottomLeftRadius: 0px});
}, function () {
    $(#user_button).css({borderBottomLeftRadius: 5px});
});

Using classes in this case would be better than setting the css directly though, look at the addClass and removeClass methods alecwh mentioned.

$(#user_button).toggle(function () {
    $(#user_button).addClass(active);
}, function () {
    $(#user_button).removeClass(active);
});

I would use the toggleClass function in jQuery and define the CSS to the class e.g.

/* start of css */
#user_button.active {
    border-bottom-right-radius: 5px;
    border-bottom-left-radius: 5px;
    -webkit-border-bottom-right-radius: 5px; /* user-agent specific */
    -webkit-border-bottom-left-radius: 5px;
    -moz-border-radius-bottomright: 5px;
    -moz-border-radius-bottomleft: 5px; /* etc... */
}
/* start of js */
$(#user_button).click(function() {
    $(#user_options).toggle();
    $(this).toggleClass(active);
    return false;
})

jQuery toggle CSS?

You might want to use jQuerys .addClass and .removeClass commands, and create two different classes for the states. This, to me, would be the best practice way of doing it.

Leave a Reply

Your email address will not be published.