Adjusting the opacity of a div while scrolling

I've searched multiple pages, but haven't found a solution that works for me. I'm trying to make the text in my div gradually become more transparent as I scroll. Can anyone help with this? Here's my code:

<script src = "/js/titleScroll.js"></script>
<div class = "header-title">


    <h1>Title</h1>
    </div>

Additionally:

$(document).ready(function() {
  $(window).scroll(function() {
    if ($(this).scrollTop() > 0) {
      $('header-title').css('opacity', 0.8);
    } else {
      $('header-title').css('opacity', 1);
    }
  });
});                         

Below is my CSS:

.header-title {
width: 80%;
height: 100px;
left: 50%;
top: 50%;
font-size: 1.5em;   
text-align: center;
transform: translateX(-50%); 
margin-top: -50px;
position: relative;
max-width: 100%;
background-attachment: fixed;
position: float;

}

.header-title h1 {
    color: white;
    text-shadow: 2px 2px 4px #d1d1d1;
    font-family: arial, sans-serif;
    white-space: nowrap;
    text-transform: uppercase;
    display: inline-block;


}

Your assistance would be greatly appreciated.

Answer №1

One issue is that currently, the opacity changes to 0.8 only when the user is not at the top of the page. To improve this, it's recommended to dynamically set the opacity based on the user's scroll position. This can be achieved by calculating the offset each time a scroll event occurs and adjusting the opacity accordingly. The function used for this adjustment can range from a simple linear change to more complex animations depending on your preference.

Below is a basic example demonstrating this functionality:

<head>
    <style>

    body {
        min-height: 4000px;
    }

    .header-title {
        position: fixed;
        width: 80%;
        height: 100px;
        left: 50%;
        top: 50%;
        font-size: 1.5em;
        text-align: center;
        transform: translateX(-50%);
        margin-top: -50px;
        max-width: 100%;
        background-attachment: fixed;
    }

    .header-title h1 {
        color: white;
        text-shadow: 2px 2px 4px #d1d1d1;
        font-family: arial, sans-serif;
        white-space: nowrap;
        text-transform: uppercase;
        display: inline-block;
    }

    </style>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
    <script>
    $(document).ready(function() {
        $(window).scroll(function(event) {
            let scroll = $(this).scrollTop();
            let opacity = 1 - (scroll / 1000);
            if (opacity >= 0) {
                $('.header-title').css('opacity', opacity);
            }
        });
    });
    </script>
    <div class = "header-title">
        <h1>Title</h1>
    </div>
</body>

https://jsfiddle.net/un2bdvfm/

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

Exploring various viewport dimensions using Django and Selenium

I am currently experimenting with testing the characteristics of specific UI elements at various viewport sizes and media query breakpoints defined in CSS. Initially, I have a setup function that initializes a headless Chrome browser with what I believe is ...

css media queries not taking precedence over default styles

Struggling to find a solution as no similar case was discovered!! To avoid adding a class name for each page, I am eager to utilize a generic class name as shown below: <div id="news"> <div class="news column">content 1</div> &l ...

Why does my computed property become undefined during unit testing of a head() method in Vue.js with Nuxt.js?

In my Vue.js + Nuxt.js component, I have implemented a head() method: <script> export default { name: 'my-page', head() { return { title: `${this.currentPage}` }; }, ... } </script> ...

Has jQuery UI Accordion taken over the design of unordered lists?

I'm having trouble with my website's navigation styling getting messed up by the jQuery accordion. The unordered list inside the .accordion div is overflowing and losing its CSS styling. I've tried adding clearStyle true and autoHeight false ...

Ways to customize PreBid.js ad server targeting bidder settings

In an effort to implement a unique bidder setting key name within my prebid solution, I have taken the necessary steps as outlined in the documentation by including all 6 required keys. Is it possible to change the key name 'hb_pb' to 'zm_hb ...

Tips for iterating through the properties of every object within a Knockout observableArray and dynamically generating a table

My observableArray is dynamically populated with SQL data, resulting in varying columns each time. I am trying to present the SQL results in an HTML table but facing issues with the code below. This is the desired output format... var viewModel = func ...

Issue with AngularJS: Dynamically generated tab does not become active or selected

Exploring an AngularJS code snippet that generates tabs upon clicking the new button. However, there's an issue where the newly created tab doesn't become active or selected automatically after creation. It seems like the one before the last tab ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

Navigating the NextJS App Directory: Tips for Sending Middleware Data to a page.tsx File

These are the repositories linked to this question. Client - https://github.com/Phillip-England/plank-steady Server - https://github.com/Phillip-England/squid-tank Firstly, thank you for taking the time. Your help is much appreciated. Here's what I ...

Top strategy for monitoring a user's advancement in reading different text segments

If you are familiar with zyBooks, I am looking to implement a similar feature where users can track the sections they have read and mark them as completed with a button. However, I am struggling conceptually with determining how best to structure my mongo ...

React JS project experiencing issues with Material UI components not functioning properly

Here is a unique version of my app.js code: import React from "react"; import './App.css'; import {Button} from "@mui/material"; function App() { return ( <div className="App"> <h1>COVID-19 T ...

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

showcasing pictures on a .handlebars/html interface

Having some trouble linking images to my .handlebars/html files in the views directory. I've already set up a public folder as per the requirements, but the linked images still aren't showing up when I view my webpage. Below is the node.js code ...

guide on adding a variable to the link_to path

In my attempt to incorporate a variable into the link_to function below: <%= link_to '<button type = "button">Players</button>' .html_safe, live_players_path(:Team => @tmf) %> Whenever I click on this link, it seems to ...

Is there a way to retrieve the properties of another function within the same component?

I am trying to place NumberFormat inside OutlinedInput and I also need different properties for the format of NumberFormat. (There will be a select window that defines which format property to use). This is what I have: import OutlinedInput from "@ma ...

Learn how to showcase a text file uploaded to a webpage with NODE js and HTML

<!DOCTYPE html> <html> <body> <form action = "/submit" method = "post"> Select a file: <input type="file" name="file"> <input type="submit"> </form> </bod ...

When using Asp.Net TextBox, the focus is lost after inputting the first character

I have created an Asp.Net web form (aspx) that includes a TextBox: <div id="field"> <asp:TextBox Id="Name" runat="server" MaxLength="50"/> </div> Whenever I type characters into the TextBox, I t ...

Show a picture outside of the dropdown container

I'm currently navigating the world of web development and I'm facing a challenge with getting an image to display outside of a dropdown div. Despite numerous attempts at setting the image's position to relative, with overflow-visible, I have ...