Maintaining Basic State With jQuery And CSS

When working on the client, you may have a number of HTML elements that have some form of logical state, e.g. coins (heads/tails), cards (face up/down), importance (high, medium, low), etc.

You could declare a variable for each element (or an array); when the use changes the state you update the variable representing the elements state and perform any UI changes.

An alternative to this which removes the need for additional variables is to represent the state of the element by which CSS classes are currently added to it.

The example below (view live example) shows one way to achieve this using jQuery. It represents a number of simulated coins and if each coin's state is heads or tails.

<!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>Maintaining basic state with jQuery and CSS</title>

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

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnClick").click(function() {
                /* Select every element that has the CSS class coin applied
                   and iterate using the each function */
                $(".coin").each(function() {
                    /* Check the each element to see if it has a tails or heads
                       css class, and 'flip' the class and the text from T->H */
                    if ($(this).hasClass("heads"))
                        $(this).removeClass("heads").addClass("tails").text("T");
                    else if ($(this).hasClass("tails"))
                        $(this).removeClass("tails").addClass("heads").text("H");
                });
            });
        });
    </script>

    <style type="text/css">
        .coin
        {
            background-color: Silver;
            font-size: 24pt;
            font-weight: bold;
            padding: 5px;
        }
        /* We don't have to define .heads and .tails to make use of
        the state maintenance, but they are defined here for visual cues */
        .heads
        {
            color: Black;
        }
        .tails
        {
            color: White;
        }
    </style>
</head>
<body>
    <h1>Maintaining basic state with jQuery and CSS</h1>
    <span class="coin heads">H</span>
    <span class="coin heads">H</span>
    <span class="coin tails">T</span>
    <span class="coin heads">H</span>
    <span class="coin tails">T</span>
    <h4>H = heads, T = Tails</h4>
    
    <form action="#">
    <input type="button" id="btnClick" value="Flip Coins" />
    </form>
    <h4>from: <a href="http://www.dontcodetired.com" title="Don't Code Tired" >Don't Code Tired</a></h4>
</body>
</html>

SHARE:

Comments (1) -

  • Anglea Tillmon

    3/6/2010 8:50:54 PM | Reply

    I have an error if I read your blog with Opera. On IE works perfect.

Add comment

Loading