Achieve a fading effect on an element as you scroll down the page

I successfully implemented a toggle audio button on my website, but now I would like it to fade in along with the scroll-to-top button that I also have (which operates similarly to the buttons on scrolltotop.com). Is there a simple way to achieve this?

Here is the HTML code I currently have:

  <div id='cornerplayer'>
<center>
  <div id='cornericon'></div>
  <div>
  </div>
  <img src=http://www.thegeekypixel.com/files/theme/Images/noaudio.png onclick="javascript:toggleSound();this.src = this.src == offImg ? onImg : offImg;">
  <audio id="audio" loop>
    <source src="http://www.thegeekypixel.com/files/theme/Music/TellMe-Killercatsfeat.AlexSkrindo.mp3">
  </audio>
  <script type="text/javascript">
    function toggleSound() {
      var audioElem = document.getElementById('audio');
      if (audioElem.paused)
        audioElem.play();
      else
        audioElem.pause();
    }
    var onImg = "http://www.thegeekypixel.com/files/theme/Images/noaudio.png";
    var offImg = "http://www.thegeekypixel.com/files/theme/Images/audioplaying.png";

  </script>
  </div>
  </center>
</div>
</div>
<div>

I have created a JSFiddle demonstration here.

The button I am trying to make fade in is the "cornerplayer" button that plays music when clicked and floats in the bottom right corner of the screen.

Is there a straightforward method to make it fade in synchronously with the scroll-to-top button?

Thank you, Oliver

P.S. Apologies for any errors, I am not very familiar with coding.

Answer №1

function checkScroll(element) {
    var topPosition = element.getBoundingClientRect().top;
    var bottomPosition = element.getBoundingClientRect().bottom;
    if((topPosition >= 0) && (bottomPosition <= window.innerHeight)) {
        fadeInElement(element)
    }
}

function fadeInElement(element) {
    var opacity = 0.1
    rate = 0.1
    var animationTimer = setInterval(function(){
        if (opacity >= 1) {
            clearInterval(animationTimer);
        }
        element.style.opacity = opacity;
        opacity += opacity * rate;
    },50);
};

Repeatedly call the checkScroll function to monitor if the user has scrolled down to the specified element. If so, the checkScroll function will trigger the fadeInElement function to gradually fade in the specified element.

To achieve this, use

checkScroll(document.getElementById("element"))
within a loop.

Answer №2

To achieve this effect, you can utilize the window.onscroll event and monitor the scrollY property in your code. Here's a sample implementation:

var windowHeight = window.innerHeight; // only calculate this value once to prevent frequent recalculations
window.onscroll = function(event) {
  var scrollHeight = window.scrollY,
      percentage = parseFloat(scrollHeight / windowHeight), // calculate current scroll percentage relative to page height
      updateOpacity = parseInt(percentage) % 10 === 0; // adjust opacity every 10%
  if (updateOpacity)
    document.getElementById('cornericon').style.opacity = percentage;
}

For an improved version of the code, refer to this updated example: https://jsfiddle.net/71uncr2g/1/

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

Programming with a combination of Javascript, Angular, and Prototype to efficiently manage and

I am in a bit of a quandary, as I wish to create a function that will clear all the properties of an object and make it available to all instances of that object. To achieve this, I have added a prototype function called clear(). Here is the code snippet: ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

The guard check may not be enough to prevent the object from being null

Hello, I am facing an issue with the Object is possibly "null" error message in my Node.js + Express application. How can I resolve this problem? REST API export const getOrderReport = async ( req: Request<{}, {}, IAuthUser>, res: Resp ...

What is the best way to make img-fluid function properly within Bootstrap Carousel?

I've been struggling to make my carousel images responsive by using the img-fluid tag, but I haven't had any success. I've attempted using !important and display: block, but nothing seems to work. I'm not sure what's causing the is ...

Tips for handling imports and dependencies in a React component that is shared through npm

Hello everyone, I'm diving into the world of sharing React components and have encountered an interesting challenge that I hope you can help me with. Currently, I have a button component in my app that is responsible for changing the language. My app ...

I'm noticing multiple repeated entries appearing when I try to set the cookie - what could be causing

Currently, I am utilizing the library js-cookie instead of my previous use of jquery.cookie. I have encountered an issue related to duplicating cookie entries. There are occasions when I invoke the following method: Cookies.set('my-cookie-name', ...

A step-by-step guide on including chess.js in your Create React App

I'm facing an issue while trying to incorporate the chess.js npm library into my Create React App. The error message "Chess is not a constructor" keeps popping up. Below is the code snippet I am using: import React from 'react'; import &apos ...

Discovering a specific value within a JSON stringified array

I am looking for a specific value within a JSON stringify array [{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":" ...

Print media not affected by Bootstrap styling

Below is the code I am using to display a table within my application: var elementToPrint = this.mainTable.get(0); newWin = window.open(""); newWin.document.write('<html><head><title>' + elementToP ...

Combining Two Tables Using jQuery

I am currently attempting to combine two tables into one using jQuery in the following manner: var table = document.createElement("table"); table.id = "mergedTable"; $("#mergedTable > tbody:last") .append($("#csvInfoTable2 > tbody").html()) ...

Set a hidden field to contain an IEnumerable of integers

Currently, I am working on a project that involves dealing with a viewmodel. [Required(ErrorMessage = "Please enter a title")] [Display(Name="Title")] public string Title { get; set; } [Required(ErrorMessage = "Description is required")] ...

By default, Nuxt 2.15.7 is automatically installed when you create a new Nuxt app

I am looking to develop a Nuxt app (version 3) using Vue. However, when I run the command npm create nuxt-app@version mousa, it automatically installs Nuxt2. How can I install Nuxt3 instead with this command? ...

Ensuring Navigation Elements Remain Aligned in a Single Line

I'm in the process of developing an interactive project that will be showcased on a touch screen. One of its key features is a fixed footer navigation. Currently, I am using floats to position the main navigation elements and within each element, ther ...

Having trouble retrieving the YouTube channel name using XPath node in Selenium and TestNG

My current task involves navigating to the YouTube website, entering the search term "qtp," and clicking on the Search button. Once on the results page, I need to extract the Channel Name. To achieve this, I used Firebug to identify the path for the first ...

Substituting Meta Viewport tag with alternative CSS method for HTML emails

In an effort to improve support for legacy Blackberrys, we made the decision to take out the meta viewport tag <meta name="viewport" content="width=device-width, initial-scale = 1.0, maximum-scale = 1.0" /> from our HTML emails. Some major email test ...

Exploring recommendations using AngularJS

I am currently working on replicating the search suggestion feature found at: where certain words are displayed as you type in the search box. Here is my HTML setup: <form ng-controller="SearchCtrl"> <input name="q" ng-model="query" ng-keyp ...

Clearing a textarea in jQuery

I'm experiencing an issue that I can't seem to resolve on my own. Any assistance would be greatly appreciated. My function designed to clear a textbox upon click doesn't seem to be working correctly: $(function() { $('textarea#co ...

Obtain the data from the hyperlink destination

Having some trouble extracting a value from an href link to use in my database operations. Unfortunately, I couldn't retrieve the desired value. Displayed below is the code for a button: <a class="btn btn-info" href="scheduleSetTime.php?id=&apo ...

Empty area beneath the body in Chrome Device Mode

Can anyone explain why there is a strange blank space under the body tag in mobile view on Chrome (other browsers like Firefox and Internet Explorer display it correctly)? Here is the simple code that I am using: <html> <meta name="viewport" con ...

Ensure your HTML5 videos open in fullscreen mode automatically

I managed to trigger a video to play in fullscreen mode when certain events occur, such as a click or keypress, by using the HTML 5 video tag and jQuery. However, I am now looking for a way to have the video automatically open in fullscreen mode when the p ...