The Toggle Function in jQuery

jQuery's Toggle function allows you to specify 2 or more functions to be called alternately on each click. Specifying 2 functions you can create a simple 2 state toggle.

The example below (see live example) specifies 3 functions to count 1,2,3,1,2,3,1...etc. Each mouse click executes the next successive function, when the last function is reached, the cycle returns to the first function.

The jQuery selector ":button[name='btnCount']" means "select all buttons or input elements of type button that also have the name of btnCount".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>The Toggle Function in jQuery</title>

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {

            $(":button[name='btnCount']").toggle(function() {
                $("#number").text("1");
            }, function() {
                $("#number").text("2");
            }, function() {
                $("#number").text("3");
            });

        });
    </script>

</head>
<body>
    <h1>The Toggle Function in jQuery</h1>
    <div id="number" style="font-size: 36pt; font-weight: bold;">
    </div>
    <input type="button" name="btnCount" value="Count" />
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired">Don't Code Tired</a></h4>
</body>
</html>

Comments (1) -

Add comment

Loading