jQuery: .toggleClass

This entry is part 18 of 33 in the series jQuery Tutorial

.toggleClass(classname):

Add or remove one or more classes from each element in a set of matched elements.

This example shows how a class is toggled to an animated object.

<!doctype html>
<html lang='en'>
<head>
    <meta charset='utf-8'>
    <title>animated demo</title>
    <style>
        div {
            background: yellow;
            border: 1px solid #AAA;
            width: 80px;
            height: 80px;
            margin: 0 5px;
            float: left;
        }

        div.colored {
            background: green;
        }
    </style>
    <script src='//code.jquery.com/jquery-1.10.2.js'></script>
</head>
<body>

<button id='run'>Run</button>

<div></div>
<div id='mover'></div>
<div></div>

<script>
    $('#run').click(function () {
        $('div:animated').toggleClass('colored');
    });

    function animateIt() {
        $('#mover').slideToggle('slow', animateIt);
    }

    animateIt();
</script>

</body>
</html>

The selector:  div:animated

The line $(‘div:animated’).toggleClass(‘colored’) selects an animated div element.

Once the run button is clicked and that animation is going on in the selected element, it will be highlighted to green.

Series Navigation<< jQuery: Common animation effects
jQuery: Hide effect >>

Leave a comment

Leave a Reply