The background image shifts dynamically with a parallax effect as the page is scrolled

I need help solving a parallax issue that I'm currently facing.

On my webpage, I have a background image positioned at the top with a parallax effect achieved through background-position: fixed. However, I now require the image to scroll along with the page, and I'm unsure how to proceed.

I think JavaScript and potentially background-position: scroll could be used to achieve this, but I'm not sure where to begin.

In the basic fiddle I provided, you can see the current parallax effect in action, but I need the image to scroll as the page does.

Any assistance would be greatly appreciated.

.image {
  height: 100px;
  width: 100%;
  background-repeat: no-repeat;
  background-size: cover;
  background-attachment: fixed;
  background-image: url('http://www.navipedia.net/images/a/a9/Example.jpg');
}
<section>
  <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo."</p>
</section>

<div class="image"></div>

<section>
  <p>"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architedicta."<br>"</p>

  <br><br>
  
<p>"Sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequinques humident. Neque porro quisquam eius."]" *(./section>

Answer №1

This code is designed to provide a parallax effect on scroll for images. You can customize the speed variable to adjust the scrolling effect according to your preference.

(function(){

  var parallax = document.querySelectorAll(".image"),
      speed = 0.5;

  window.onscroll = function(){
    [].slice.call(parallax).forEach(function(el,i){

      var windowYOffset = window.pageYOffset,
          elBackgrounPos = "50% " + (windowYOffset * speed) + "px";

      el.style.backgroundPosition = elBackgrounPos;

    });
  };

})();

To see this code in action, visit: https://jsfiddle.net/ksugkmoh/

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

Django RGBField cannot locate jQuery

Working on a project that utilizes an RGBField, the following script is injected into the template (nested deep within django's structure, as its exact location remains elusive): <script type="text/javascript"> (function($){ ...

How can we export data to excel using react-export-excel while ensuring certain columns are hidden?

Greetings! I believe the title gives you a clear idea of my dilemma. When exporting data, there are no errors - my goal is to hide the Excel column when the checkbox is unchecked or false, and display it when the checkbox is checked or true during export. ...

PHP Ajax request to the same PHP script resulted in a response of null

As part of my development process, I am creating a single-page script called category.php to handle category management. This script includes an input button that triggers an AJAX call. <input type="button" id="btn" /> The jQuery code is u ...

What could be causing the post method to fail in this AngularJS example?

After successfully reading a JSON file in my sample code, I encountered an issue when trying to update the JSON file. The error message "Failed to load resource: the server responded with a status of 405 (Method Not Allowed)" appeared, even though the data ...

How can I make my iPad switch to landscape mode in my specific situation?

I'm attempting to trigger the landscape mode on an iPad web browser, including the address bar and tabs, when a user clicks a link. Here's what I currently have: <div> <a ng-click="click me()" href="www.cnn.com">Click me</a&g ...

What is the best way to manage the retrieved data in a situation where I am utilizing async-await along with the useEffect hook?

I need to retrieve a player's statistics based on the input provided by the user, and then show it. I am facing challenges in storing the retrieved data using the useEffect hook. Any suggestions for a more efficient approach? import React, { useEf ...

Internet Explorer 7 is failing to enlarge a div in order to accommodate the content loaded

When loading content into divs using $.load(), it works smoothly in Firefox and Chrome, but I'm facing issues with IE7. The page isn't getting redrawn after the content is loaded, resulting in most of the content being cropped. Despite reading va ...

What is the best way to save the output of a middleware in express js so that it can be conveniently accessed by the rest of the

Currently, I am working with a middleware that returns an object. My goal is to save this object so that other parts of the application can utilize the data it contains. How can I achieve this? This snippet is from my app.js file: import { myMiddlewareFun ...

What are the steps to sending HTML emails from the default mail client on Mac and PC operating systems?

Currently, I am in the process of creating a website that allows clients to easily send an email with the content they are viewing. I want users to click on a button which will open their default mail client (compatible with both Mac and PC) and automatica ...

Experiencing a JSONP issue with an 'Access-Control-Allow-Origin' error

When working with PHP, I often use the following code to echo JSONP formatted data: echo $_GET['callback'] . '('.json_encode($arr).')'; In my AngularJS (JavaScript) code, I make a GET request like this: $http.get('http ...

When trying to save an image using multer's storage, the error message "ENOENT: file or directory not found" is displayed. It is important to note that symbols are not causing

Whenever I try to save an image using multer's storage feature, I encounter the following issue: [Error: ENOENT: no such file or directory, open 'C:\MAMP\htdocs\Chat Backend\public\images\servers\1596819056816AF ...

Tips for Looping through an Object within another Object

Is there a way to retrieve values from an Object that contains another Object nested inside? I am not overly concerned about the keys, but it would be helpful if I could access them as well. Here is an example of the response: res = {data: {name: 'na ...

Use jQuery to clear the content within a div element following the removal of an element

A dynamic generation of checkboxes is introduced to div1: $.each(json, function(idx, obj) { $("#tbl1").append('<input type="checkbox" id='+obj.firstId+' onclick=nextPopulate('+obj.firstId+'); >'); } Upon selection, ch ...

Creating a post request in Express.JS with an empty object

Currently, I am working with Express version 4.18.2. I have created routing and controller files along with an HTML form that uses the POST method. However, when I submit the form, I attempt to display the req.body object sent in the request through the co ...

Switch up the picture when you press on it

I have a task involving a table where I want to switch out an image in the <td> when it is clicked, using a URL that I specify beforehand. The URL of the image will be provided when clicking on a link within the page. For example: index.html?type=d ...

What is the reason behind capitalizing Angular CLI class file imports?

After creating a basic class in Angular using the CLI starter, I encountered an issue when trying to use the imported class. Instead of functioning as expected, it returned an empty object. Through troubleshooting, I discovered that simply changing the fil ...

Is there a method to incorporate scss into a project without requiring a separate stylesheet?

I am currently working on a Gatsby application that utilizes SCSS. My code snippet looks like this: import React from "react"; import styles from "./mosaic.module.scss"; import Tile from '../tile/tile'; const Mosaic = (): JSX.Element => ( ...

Function in AngularJS to increment counts based on matching names

Check out my angular application on this Plunker link The text area in my app contains data in the format of (key, count). My goal is to sum up these values using the calc() function. When the user clicks the button, I want the total summation to be disp ...

Ways to navigate by percentage in react

I'm working on a flexbox that scrolls horizontally with boxes set to 25% width. Currently, I have it scrolling by 420px which is causing responsive issues. Is there a way to implement the scroll using percentages instead of fixed pixel values in React ...

Attempting to retrieve the mesh object using A-Frame's getObject3D('mesh') function results in an undefined value after several attempts

In an attempt to obtain a bounding box for an obj-model in A-frame, I came across two helpful links on stackoverflow that I will reference here: How to get bounding box information from a 3D object in A-frame? Any way to get a bounding box from a three.js ...