In previous jQuery animation post, the curtain picture Div layer moved to the right when visitor click on the button. However if the visitor click on the button again, nothing will happens. Most visitors will wonder if there is a bug with the animation. Therefore this is better to modify the jQuery codes a bit so that the curtain picture will be moving back to the original position when the visitor click on the button again.

Here’s the modified jQuery animation effect:

The complete jQuery codes of the above animation effect are:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Slide Div Layer Left and Right</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
    $("document").ready(function() {

        // Get the outer height of #picture Div
        var widthShift = $("#picture").outerWidth();

        $(".slideRight").click(function() {

            if ( $(this).is(".slideRight") ) {

                // Move the curtain to the right by the outer width of #picture Div layer
                //  in 5 seconds when the button is clicked.
                $("#picture").animate({ "left": "+=" + widthShift + "px" }, 5000);

                // Toggle the class
                $(this).toggleClass("slideRight slideLeft")

            } else {

                // Move the curtain to the left by the outer width of #picture Div layer
                //  in normal speed when the button is clicked.
                $("#picture").animate({ "left": "-=" + widthShift + "px" });

                // Toggle the class
                $(this).toggleClass("slideRight slideLeft")
            }

        });                        

    });
</script>
</head>

<body>

<h1>jQuery Animate Div Layer Left and Right</h1>

<div id="frame">
    <div id="pageContent"></div>
    <div id="picture"></div>
</div>

<div style="width:282px; text-align: center; margin-bottom:10px;">
    <input type="button" class="slideRight" value="Click Here Animate Curtain to Left/Right" />
</div>

<div style="width:282px; text-align: center"></div>
</body>
</html>

The jQuery codes are almost the same as the animation example in previous post. In this jQuery example, I simply use the toggleClass() method to swap between the CSS class of the button. Here’s the magic of jQuery toggleClass method:

  • When the web page open, the class of the button is: slideRight. Therefore the curtain div layer will be moved to the right when the button is clicked.
  • After the button is clicked, the class of the button will be swapped to: slideLeft. Hence the curtain div layer will be moved to the left when the button is clicked again.
  • The class of the button repeat over again when the button is clicked again.

jQuery animation is really fun and easy!