Friday 9 December 2016

Moving Background image in JavaScript.


Hello guys, I have already made a video tutorial on YouTube demonstrating how to make a background image moves vertically in a continuous manner.

The code snippet is very minimal and simple to understand.

Below is the code snippets for the html, css and javascript files.

HTML File

For the html, you need to generate as much paragraphs as you can to fill the page so you can see clearly the effect we are trying to demonstrate. 

Note: This tutorial is for beginners in web development, so don't feel sleep off if you are already a nerd in the field. :-)

If you are using emmet plugin, you can easily generate these paragraphs using the following
p*20>lorem and press tab. So I will not show all the content of the body here.


<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Moving Background Image</title>
 <link rel="stylesheet" href="css/app.css">
</head>
<body>

 <div class="wrap">
            <!--Your content here-->
  
 </div>
<script src="js/app.js"></script> 
</body>
</html>

CSS code Listing.


body{
 background-image: url('../img/desert.jpg');
 background-repeat: repeat;
 background-size: cover;
 background-attachment: scroll;
}
.wrap{
 color: #ccc;
}

In the above listing, you replace the "desert.jpg" with your own image.

JavaScript Code Listing

window.onload = function(){
 var body = document.querySelector('body');

 var x_pos = '0px';
 var y_pos = 0;

 setInterval(function(){
  body.style.backgroundPosition = x_pos + ' ' + y_pos + 'px';
  y_pos++;
  
 }, 20);
}

The above code listing is the most important of all.
CSS background position is the one doing the magic.
You use background-position to determine where you want to position the background image of your web page
It is used like: background-position: "50px' "60px";
The first value is the X position and the second is the Y position.
In our case, we want to continuously updating the Y value by incrementing it, that is why we used it in
javascript.
setInterval() function takes a function, in our case an anonymous function and a timer value that shows
at which time in milliseconds will the function runs.
So in every 20 milliseconds, you change the background position by updating its Y-coordinate value.