jQuery css() set css background position update horizontal

Description

jQuery css() set css background position update horizontal

View in separate window


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>jQuery Parallax Effect</title>
        <style>
div { width:100%; height:1000px; position:absolute; left:0; top:0; }
#background { background:url(image7.png) repeat-x 0 0; }
#midground { background:url(image6.png) repeat-x 0 0; }
#foreground { background:url(image5.png) repeat-x 0 0; }
#ground { background:url(image4.png) repeat-x 0 100%; }
</style>// w  ww .  j  av  a  2s.  c  o  m
        
    </head>
    <body>
        <div id="background"></div>
        <div id="midground"></div>
        <div id="foreground"></div>
        <div id="ground"></div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
         <script>
            $(function () {

                //cache selectors
                var bg = $("#background"),
                    mg = $("#midground"),
                    fg = $("#foreground");
                    
                //add handler for right arrow key
                $(document).keydown(function(e) {
                    
                    //move character when right arrow key pressed/held
                    if (e.which == 39) {

                        //animate background-positions
                        bg.animate({ backgroundPosition: "-=1px" }, 0, "linear" );
                        mg.animate({ backgroundPosition: "-=10px" }, 0, "linear" );
                        fg.animate({ backgroundPosition: "-=20px" }, 0, "linear" );                        
                    }
                });
            });
        </script>
    </body>
</html>



PreviousNext

Related