Dynamic mouse parallax effect enhances the experience of a full-screen responsive background

I am looking to create a background that covers the entire viewport, similar to the example shown here: https://css-tricks.com/perfect-full-page-background-image/

Additionally, I want to have 5 images stacked on top of each other (essentially 5 layers of the same original graphic) that all respond and resize at the same rate. This will allow me to implement a parallax effect on each layer, so that when the mouse moves, each layer moves at a slightly different rate.

I am struggling with figuring out how to load these images. Should I load them in the HTML body or in the CSS? And how do I ensure that they are layered on top of each other (I have tried using z-index without success).

Currently, I am attempting to load each image as a background, but this approach is not working. I am in need of a different solution.

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

div.home5 {
  height: 100%;
  margin: 0;
  padding: 0;
  background: url('https://www.w3schools.com/howto/img_avatar.png') no-repeat center center fixed;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: -5;
}

div.home4 {
  z-index: -4;
  height: 100%;
  margin: 0;
  padding: 0;
  background: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNSvAuOC-j9NLym8Duah8cGaA_6vhov8KGH8E29j2HeHszAO1k') no-repeat center center fixed;
  background-size: cover;
  background-repeat: no-repeat;
}

div.home3 {
  height: 100%;
  margin: 0;
  padding: 0;
  background: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRqCM25IBWmfkxQ3Kg_q8_SxQlBIckh-alD0sf2GDwgjN0XUm9u') no-repeat center center fixed;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: -3;
}

div.home2 {
  height: 100%;
  margin: 0;
  padding: 0;
  background: url('https://www.soccercric.com/uploads/news/images/1309164275952e2e897191.png') no-repeat center center fixed;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: -2;
}

div.home1 {
  height: 100%;
  margin: 0;
  padding: 0;
  background: url('http://www.gclogistics.ca/wp-content/uploads/2015/02/stefan-1-270x270.png') no-repeat center center fixed;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: -1;
}
<!-- 'Pages' -->
<div id="page1">
  &nbsp;
</div>
<div class="home5">
  &nbsp;
</div>
<div class="home4">
  &nbsp;
</div>
<div class="home3">
  &nbsp;
</div>
<div class="home2">
  &nbsp;
</div>
<div class="home1">
  &nbsp;
</div>

Answer №1

To achieve a parallax effect, you need to set all the div elements to have a CSS property of position:fixed and then assign each of them an image as a background-image, causing the images to stack on top of each other.

Next, you should add an event listener for mousemove which will move the images in response to the mouse movement, creating a parallax effect.

Here is the code snippet that demonstrates this functionality:

var currentX = '';
var currentY = '';
var movementConstant = 0.010;

$(document).mousemove(function(e) {
  if(currentX == '')
    currentX = e.pageX;
  var xdiff = e.pageX - currentX;
  currentX = e.pageX;
  if(currentY == '')
    currentY = e.pageY;
  var ydiff = e.pageY - currentY;
  currentY = e.pageY;
  $('.parallax div').each(function(i, el) {
    var movement = (i + 1) * (xdiff * movementConstant);
    var movementy = (i + 1) * (ydiff * movementConstant);
    var newX = $(el).position().left + movement;
    var newY = $(el).position().top + movementy;
    $(el).css('left', newX + 'px');
    $(el).css('top', newY + 'px');
  });
});
html{
  overflow:hidden;
}
div{
  width:100vw;
  height:100vh;
  position:fixed;
  
}
.h1{
  background-image:url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_bg.jpg');
  background-repeat:no-repeat;
  background-size:cover;
}
.h2{
  background-image:url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_02.png');
  background-repeat:no-repeat;
  background-size:cover;
}
.h3{
  background-image:url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/272781/ilu_man.png');
  background-repeat:no-repeat;
  position:fixed;
  margin-left:80%;
  top:80%;
}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
  </head>
  <body>
    <div class="parallax">
      <div class="h1"></div>
      <div class="h2"></div>
      <div class="h3"></div>
    </div>
  </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Validating Forms using Javascript

I'm struggling to understand why I'm not getting any error or success messages when I click the submit button. My goal is to validate strings in an HTML form to ensure they are not null or too long. Both the developer's tools and the Online ...

Customizing input tags

Greetings everyone, I have encountered a dilemma : <input type ="file" name ="fileUpload"> I created a file input that shows "choose a file" by default. I'm not too fond of it and would like to make it look more like a button. However, when I ...

The PHP script is displaying all content following the echo statement

Currently in the process of constructing my inaugural website. Starting off by creating it on my laptop and will eventually upload it to my hosting service. The main focus of this website is to provide a searchable database containing information about fam ...

Angular 5: Transforming and Concealing CSS Class Names

Can CSS selectors be renamed or obfuscated in an Angular CLI project? Many top websites like Google and Facebook use randomized CSS names for various reasons, such as preventing website scripting through targeting static class names. I would like to imple ...

Manipulating Div Content with JQuery Based on Checkbox Selections

My goal is to extract content from a hidden div that contains an unordered list with specific classes and move certain list elements into placeholder divs based on checkbox values. Initially, when no checkboxes are checked, I want all list elements in the ...

What is the best way to navigate to the bottom of a page when new data is added?

I've created a chat feature in my Ionic app, but the issue is that when a user receives a new message while being on the chat screen, the view doesn't automatically scroll down to show the new message. The user has to manually scroll down to see ...

Flex Display with Bootstrap for Responsive Tables

Is there a way to display the scrolling of a Bootstrap table using a flex container? https://getbootstrap.com/docs/4.4/content/tables/#responsive-tables I am looking for the JSFiddle example with DIV elements. Removing the display:flex from .flex_containe ...

Flyer - Chart "dimmed" and unselectable when dimensions are specified as a proportion

I am currently working on displaying a map within a container. I have successfully been able to display the map by setting its size to a specified number of pixels. However, my goal is to have the height of the map adapt to the size of the container dynami ...

Adjust the size and orientation of an image according to the dimensions of the window and the image

As I delve into HTML and Javascript, I am facing a challenge with resizing an image based on the window size. The goal is for the image to occupy the entire window while maintaining its aspect ratio during resizing. Additionally, if the window size exceeds ...

Align image within box using Bootstrap

My project screenshot is displayed below. The red line separates the current state from the desired outcome. I am struggling to make it fullscreen, meaning it should extend all the way to the corners. Despite trying various methods with Bootstrap 4, I have ...

What is the best way to connect a fresh post to a different URL in ReactJS and Redux?

Currently, I am working with Redux and ReactJS to develop a discussion platform. One of the key features I am trying to implement is where users can input the title and content of their post, which will then be submitted to create a new post. After submit ...

styled components are having issues with background gradients and opacity not functioning properly

Hello, I am currently working with styled components and have the following global style code: const GlobalStyle = createGlobalStyle` html{ font-family: roboto; background: linear-gradient(45deg,rgba(137,255,255,0.5),rgba(161,252,143, 0 ...

Unable to retrieve the value of ng-model using $scope

Having some trouble getting the ng-model value when clicking a button that triggers a function to add each ng-model value to an object. Interestingly, when trying to get the value of $scope.shipNameFirst, it shows up as undefined in the second example. I& ...

Tips for eliminating flicker upon the initial loading of a webpage caused by dynamic changes in CSS styles through JavaScript

Struggling with the load order of my CSS and JavaScript... Currently, I have a div with a blue background that is styled to appear sliced diagonally. However, upon initial page load (or CTRL+SHIFT+R), there's a brief moment where the slice effect doe ...

Guidelines for choosing a dropdown menu option using jQuery in a WordPress photo gallery

First off, take a look at the screenshot to understand what I'm trying to accomplish: Within WordPress, after clicking on "New Post" and then on the "Add Media" button, a pop-up image gallery appears with an image filtering drop-down menu. My goal is ...

Link the parameters of two polymer elements within a repeat template

In this scenario, my goal is to securely bind attr and attr1. These two variables should be independent from the variable data, unlike other attributes in use. I want each iteration to have its own set of bound components, rather than sharing one data obje ...

Unable to hide content in Shopify using @media

How can I hide a Facebook like button when the browser window is resized to a certain width? This is the code I am using: @media all and (max-width: 300px) { .fb-like { float: right; display: none; } } While this code works on regular websites, it do ...

Troubles with Borders and Padding in HTML Elements

Hello everyone, I'm currently facing an issue trying to neatly fit a textbox, select menu, and button all within the same sized div. Each element seems to have strange borders/margins causing them not to display properly (the button ends up below the ...

A guide on updating CSS content dynamically within ExtJS

In my resource folder, I have a CSS file that contains some values which I need to change or add based on certain conditions. However, I'm struggling to figure out how to achieve this. Here is an example of the code: triggers: { clear: { ...

The styling of HTML elements is ineffective when using scoped styles

I'm facing an issue where my element styling doesn't seem to work when using the scoped attribute. Upon inspecting the element, it appears that the styling is not being applied when using scoped. The reason I need to use scoped is because I want ...