Simple Parallax effect tutorial using Javascript

Parallax Effect is quite a beautiful trick that you can put on to your website to showcase your products or content in a very cool way. Confused lets see an example #1 this is how you can view the content but obviously its the advance way of doing it . So I’ll be doing in a more simpler way but the concept will be same .


So parallax is basically a combination of two new fashion of web design workflow one is Single Page design and the other is parallax scrolling . Single Page design means every thing in one page where as parallax scrolling means that as you scroll the page its background image moves slower than the speed at which you scroll .

Lets see some code

I started with using a simple HTML document page with style containing below code


position: relative;
z-index: -1;

margin-top: -10px;
background-color:#4c4c4c;   //grey color
position: relative;

and in the body part
<img id="image" src="ime.jpg" height="710px" width="100%">
<div id="content"></div>

where ime.jpg is my image file. and content is a div ID selector that is basically the grey color background to show you the effect .Now the javascript code add it inside the head below the style close tag . As you know js should be written inside the script tag here’s the code .

<script type="text/javascript">
var ypos,image;
function parallax(){
image=document.getElementById('image'); ypos * .6 + 'px';
window.addEventListener('scroll', parallax);

So we have created a function called parallax() the first line inside the function gives the Y axis offset means the scroll location at y-axis , second line gets the element by using the id selector from the html body ie image and the third line does the actual changes to the top of the image element in the document . and the last line ie the window.addEventListener which basically calls the function parallex and has a type ‘scroll’.

Lets play with it , change the .6 value to .2 or .1 but not more than 1 and see the changes . If you saw the changes then you have successfully completed the tutorial . feel free to comment down below.