Decrease the transparency of the background image when scrolling, limit the minimum transparency allowed

I'm attempting to achieve a unique effect with the background image, where its opacity reduces on scroll to a minimum of 0.5 once it goes past the landing page. I've been using vanilla JavaScript for this purpose. I initially tried incorporating Math.max() within the scroll function to ensure the image only drops to 0.5, but encountered an issue where the image remained at 0.5 for all pages.

My goal is to have the landing page always display at full opacity (1), while all other pages should have an opacity of 0.5. Although I was successful in creating the scrolling animation, I need assistance in stopping the opacity change at 0.5.

const landingHeight = document.getElementById("section-landing").offsetHeight;
window.onscroll = function() {
 const opcFilter = (window.pageYOffset/ landingHeight);
  document.body.style.background = "linear-gradient(rgba(255, 255, 255, " + opcFilter + "), rgba(255, 255, 255, " + opcFilter + ")), url(https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg) no-repeat";
}

Answer №1

To achieve the desired effect, make sure to include Math.min instead of Math.max in your script: (It is recommended to add a window.onload for the code to run smoothly within the snippets)

window.onload = () => {
  const landingHeight = document.getElementById("section-landing").offsetHeight;
  window.onscroll = () => {
    const opcFilter = Math.min(0.5, window.pageYOffset / landingHeight);
    document.body.style.background = `linear-gradient(rgba(255, 255, 255, ${ opcFilter }), rgba(255, 255, 255, ${ opcFilter })), url(https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg) no-repeat`;
  }
}
body {
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica, sans-serif;
  scroll-behavior: smooth;
  background: linear-gradient(rgba(255, 255, 255, 0), rgba(255, 255, 255, 0)), url(https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg);
  background-repeat: no-repeat;
  background-attachment: fixed !important;
  background-size: cover !important;
  background-position: center top !important;
}

nav {
  width: 100%;
  background: #C1C8D0;
  overflow: hidden;
  position: fixed;
  top: 0;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  float: right;
}
...
</body>

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

Retrieve the value of a CSS class property regardless of whether it is actively being utilized

I am facing a dilemma where I need to determine the value of the 'width' property for a css class named 'foo' (example: ".foo { width:200px}" ). However, there may not be an element with this class in the dom yet. My goal is to retrie ...

CSS Opacity Issue

Why is the article transparent? Despite my efforts to search online for similar instances, I am surprised at not finding anything and feeling quite puzzled about what steps to take next. body { background-color: #000000; opacity: 0.8; background-i ...

Show a jQuery Dialog/Popup, followed by updating a hidden field with the outcome of the dialog

The Challenge On a webpage, I have a form that includes a hidden field named "generic_portrait". My goal is to prompt the user to click a link labeled "select portrait". This action should trigger a Dialog/Popup using jQuery, which will be determined base ...

How can the scrollbar functionality and grey border box/outline be removed from the canvas?

I am currently developing a Django project where I have two canvas elements stacked on top of each other. The top canvas has functionality that allows me to mouseover it and reveal an image loaded into the canvas below. While this functionality works well, ...

Having trouble getting Visual Studio Code to execute my build command in launch.json

Whenever I run this specific command in a command prompt, everything works perfectly: browserify -u jquery /public/index.js -t babelify -o /public/scripts/bundle.js & node /server.js But when attempting to integrate it into the program section of my ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

Submitting incomplete values from a Jquery form to a MySQL database

I'm having an issue with my IntelXDK HTML5 mobile app where the form is submitting empty values to the MySQL database. Here is the HTML code for my single file app: <label class="item item-input widget uib_w_6 d-margins" data-uib="ionic/input" da ...

Tips for showcasing boxed numerical characters on a website

Currently, I am tackling a project that involves converting a PDF into HTML. The original .ai file shows some numeric characters inside a box: https://i.sstatic.net/dAMU2.png Even though I am aware that the font used in the file is GothicMB101Pro DeBold- ...

Custom input boxes in AngularJS for unique validation method

I've recently implemented some new custom input boxes, which you can check out here. However, I'm facing an issue with the validation that used to work perfectly fine. My goal is to have the line turn red when there's a validation problem, ...

Is there a way to incorporate a fade-in effect when I trigger the expand function in this script?

I recently came across a jQuery plugin for expanding and collapsing content. I am interested in adding a fade-in effect to this plugin specifically when the EXPAND button is clicked. How can I accomplish this? $(document).ready(function () { var maxlines ...

ReactJS - Opt for useRef over useState for props substitution

Presented below is my ImageFallback component, which serves as a backup by displaying an svg image if the original one is not available. export interface ImageProps { srcImage: string; classNames?: string; fallbackImage?: FallbackImages; } const Im ...

A guide to troubleshooting the error 'response.json is not a function' within an async/await function

Having trouble converting my response to JSON. I keep receiving a TypeError: response.json is not a function error. Can someone please help me figure out what's going wrong? Thanks in advance. componentDidMount(){ this.timingFunction = se ...

What can cause my function to return true on the server but false on the client side in Meteor.js?

I am facing an issue with the hasCompleted function which returns true or false on the server side: Smaples.helpers({ hasCompleted(userId) { // … switch (this.frequency) { case Frequency.ONE_TIME:{ return measures.fetch().every(mea ...

Error trying to import: 'Navbar' is not available from '@/components/Navbar' (imported as 'Navbar')

Having trouble adding a navbar and footer to my nextjs project without using layout. Here is how my files are structured. https://i.sstatic.net/D7Fx3.png Check out the code below: import './globals.css' import { Inter } from 'next/font/goo ...

JavaScript: The initial function call does not correctly switch the "boolean" in Local Storage

I'm currently developing a project that involves implementing a tutorial overlay. My goal is to have the overlay toggle on and off using a button, while also ensuring that the state of the button is remembered between page transitions so that users do ...

tips for aligning figcaption vertically to image within figure

Is there a way to vertically align the text in the figcaption with the image in this figure? Check out an example here: http://jsfiddle.net/YdATG/1/ Here is the HTML code: <section class="links"> <a href="#"> <figure class="grid-pa ...

How to use v-if in Quasar framework to hide a Vuejs component on the signup page

Currently, I am utilizing the Quasar drawer feature in my application. On the signup view, I would like to hide the drawer. While my current code successfully hides the drawer, an issue arises when I reload the signup page as it briefly renders in the DOM ...

Ways to align the content in the middle of a div with CSS

My website is functioning perfectly on large devices, but I am facing an issue when trying to center the icon below the slider on mobile devices. I have used the following code in the icn class: .icn{ margin:0 auto; } However, the icon is not centered as ...

Creating dynamically adjustable columns in Bootstrap

I've created a simple code for experimentation purposes: <!doctype html> <html lang='en'> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" ty ...

Diving deeper into the functionalities of the express.js response module

I am currently developing an application that requires the use of two different templating languages. The code snippet below demonstrates how I am incorporating Jade and Lodash templates: app.get('/route1', function(req, res) { res.render(&apos ...