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

Using JavaScript build-in functions in a Vue template allows for enhanced functionality and

Is there a way to utilize JavaScript built-in functions within a Vue template? {{ eval(item.value.substring(2)) }} I attempted to use the JS function eval() in {{}}, but encountered several errors such as: [Vue warn]: Property or method "eval" i ...

Obtain the ID of the textarea element when it is clicked

Is there a way to retrieve the id of a textarea that was focused when another element is clicked? I have tried using $(':input:focus').attr('id'), but the textarea quickly loses focus after the click, making it impossible to obtain the ...

Generating a JSON Array Made up of JSON Elements Using JQuery

Currently, my goal is to send a JSON Object to the backend. Essentially, I aim to retrieve the input from 2 textfields and a list of all selected checkboxes. Below is an excerpt of my JavaScript code: function insertNewHero() { var selectedAbiliti ...

Appears as though time is slipping away during date conversions

I seem to be experiencing a strange issue where I lose a day when transitioning between MySQL and my JavaScript code, and I can't seem to figure out why. When I insert a date into the database (for example, 10/14/12), it appears as 10/13/12 in the dat ...

Guide to altering the color of the row that is clicked in a table using css and jquery

Is there a way to change the text color of a row in a table when it is clicked, similar to an example like this but without changing the background color? The code I have tried is not working for me. Below is a snippet of the code I am using: $("#myTab ...

Can a nofollow attribute be added to concealed modal content in Bootstrap?

Query: I am dealing with a situation where I have a significant amount of disclaimer text within a modal on my website. This text is initially hidden (display:none) until a user clicks a button to reveal it. I want to prevent search engines from indexing t ...

The Jquery AjaxStop event fails to trigger, but AjaxStart works perfectly

While I was working with APIs, I encountered a roadblock. I have a Jquery function that retrieves data from an API. To prevent a "reposition" effect, I need the function to wait until all calls are made before triggering another function to place all the ...

What is the best way to incorporate a smooth transition for an object as it appears on the screen in React?

After configuring my code to display a component in the HTML only if a specific hook is set to true, I encountered an issue with a CSS transition. The problem arises because the 'open' class is triggered at the same time the element becomes true, ...

Retrieve JSON information from a document through JavaScript

Is it possible to fetch JSON data using JavaScript without relying on jQuery? I am only interested in retrieving data using pure JavaScript. Here is an example of my JSON file: {"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_d ...

Making an "associated" route the active route within Aurelia

In my Aurelia application, I have implemented two routes: a list route called Work and a detail route called WorkDetail. Currently, only the list route is visible in the navigation menu: Home | *Work* | Contact | . . . When users navigate to the W ...

Is there a way to automatically change specific characters as a user types in an input field?

I'm facing an issue with replacing some characters dynamically. The goal is to ensure that user-input text is URL-friendly for constructing a URL: function slugify(string) { const a = "àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïí ...

Creating an indentation on one side of a div using CSS for a visually appealing effect

https://i.stack.imgur.com/io6m0.jpg I'm in the process of trying to create two shapes using CSS. I've been able to almost achieve the first shape on the left, but it extends out too far. As for the second shape, I'm having difficulties cre ...

Tips for swapping out the content within a "li" element

I am dealing with a situation where I have approximately 100 pages, all containing an <ul> tag, but the issue is that I need to enclose each list item within a <span> tag. Below is the code snippet I have tried: <ul style="list-style-type: ...

Ways to eliminate an item in a JSON structure?

Allow me to elaborate. I received a JSON containing numerous objects: data = [{"id":"784","label":"blah","publisher":"me"},{"id":"785","label":"bleh","publisher":"you"},{"id":"786","label":"blih","publisher":"she"}]; For instance, I am looking to elim ...

How can we pass the onClick prop from a child component to a parent component in React with Typescript?

Currently, I am utilizing React along with TypeScript. I am curious about the process of passing an event from the parent component to a child component using props. Here is an example for better understanding: parent.tsx const ParentComponent: React.F ...

Managing the `selected` property of an option in React/NextJS

I have been working on a website and encountered an issue with a dynamic select box in React. Despite the functionality of my app being intact, I am struggling to add the selected property to an option once it is chosen. Is there a more effective way to ...

Tips on changing the background image when hovering over a list item and a link with CSS

I have been attempting to adjust an image that is nested within a link which is nested inside a list. My initial idea was to use the image as a background picture. The issue arises when I try to position the background picture correctly with respect to th ...

What is the best way to incorporate currency formatting into a table using sumtr and datatables?

I have a table where I am utilizing sumtr for the table footer, and displaying all the information within datatables. My requirement is to show all the values as currency. However, I am unable to modify the values after sumtr because it won't be able ...

Invoking one service from another service in AngularJS

I'm trying to access a service from another service and use the returned object for some operations. However, I keep encountering a TypeError: getDefinitions is not a function error. Here is the code for my services and controller: definitions.servi ...

Caution: Highlighting Non-ASCII Characters in Your Django Form

Looking to implement client-side Ajax validation for my Django form. The goal is to alert users in real-time if any non-ascii characters are detected as they type in a field. Originally considered using python to check for ascii characters in the form&apo ...