The scroll-to-top button refuses to fade out

I am currently facing a challenge with my scroll to top button not functioning properly. It seems like there is an issue arising from another animation that I can't seem to pinpoint. Specifically, when the other animation is triggered at "scroll hits 500", the scroll to top button fails to fade out and disappear as expected.

$.chain = function() {
    var promise = $.Deferred().resolve().promise();
    jQuery.each( arguments, function() {
      promise = promise.pipe( this );
    });
    return promise;
  };  

  function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
      return pageYOffset;
    }
    else{
      var body = document.body; //IE 'quirks'
      var docElement = document.documentElement; //IE with doctype
      docElement = (docElement.clientHeight)? docElement : body;
      return docElement.scrollTop;
    }
  }    

  $(window).on("scroll", function(){
    if(getScrollTop() >= 600){
    $(window).off("scroll");
      var animations = $.chain(function() {
        return $('#animate1 img').fadeIn('slow').delay(400);
      }, function() {
        return $('#animate2 img').fadeIn('slow').delay(400);
      },  function() {
        return $('#animate3 img').fadeIn('slow');
      });
    };
});

jQuery(document).ready(function() {
var offset = 300;
var duration = 500;
jQuery(window).scroll(function() {
    if (jQuery(this).scrollTop() > offset) {
        jQuery('.scroll-top').fadeIn(duration);
    } else {
        jQuery('.scroll-top').fadeOut(duration);
    }
});
});

Your assistance in resolving this issue would be greatly appreciated. Thank you.

Answer №1

$(window).off("scroll"); is effectively removing the scroll event that you are currently listening to for fadeIn and fadeOut effects.

While I have not personally tested it, another approach could be to utilize event namespacing?

For instance, you could try something like this:

$.chain = function() {
    var promise = $.Deferred().resolve().promise();
    jQuery.each( arguments, function() {
      promise = promise.pipe( this );
    });
    return promise;
  };  

  function getScrollTop(){
    if(typeof pageYOffset!= 'undefined'){
      return pageYOffset;
    }
    else{
      var b = document.body; //IE 'quirks'
      var d = document.documentElement; //IE with doctype
      d = (d.clientHeight)? d : b;
      return d.scrollTop;
    }
  }    

  $(window).on("scroll.foranimations", function(){ // event name
    if(getScrollTop() >= 600){
    $(window).off("scroll.foranimations"); // event name
      var animations = $.chain(function() {
        return $('#animate1 img').fadeIn('slow').delay(400);
      }, function() {
        return $('#animate2 img').fadeIn('slow').delay(400);
      },  function() {
        return $('#animate3 img').fadeIn('slow');
      });
    };
});

jQuery(document).ready(function() {
    var offset = 300;
    var duration = 500;
    jQuery(window).on("scroll.forfading", function() { // event name
        if (jQuery(this).scrollTop() > offset) {
            jQuery('.scroll-top').fadeIn(duration);
        } else {
            jQuery('.scroll-top').fadeOut(duration);
        }
    });
});

Take note of the distinctive event names used: scroll.foranimations and scroll.forfading

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

Issues with object changes not reflecting in Vue.js 2.0 component rendering

I am facing an issue where my object is not updating immediately after a click event. It appears that a manual refresh or clicking on another element is necessary for the changes to take effect. How can I ensure that the object updates without the need for ...

Link-defying button

I'm developing a website with a homepage that serves as an entry point to the rest of the site (it welcomes the user and allows them to click anywhere to access the main website). The following code accomplishes this: <template> <div onc ...

Tips for storing and retrieving high scores in a JavaScript game

I've just finished creating a JavaScript snake game and now I'd like to add a "scores" option that displays the top 10 players along with their names and scores. My initial plan was to create an object containing the player's name and score ...

What is the best way to initiate a function from within another function while working with ReactJS?

Seeking guidance on how to trigger a Redux state change by calling a function from another function using the onClick event. Currently, I am able to invoke the Jammingmenu upon clicking an icon, however, no action is performed or alert displayed. Any assis ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...

Having difficulty with my async custom react hooks. Is there a way to wait for the result of one hook before using it in another hook?

Having some difficulty working with custom react hooks. I've created 2 custom hooks - one for fetching an ID and another for fetching a profile using the previously fetched ID. Since the second hook is dependent on the ID, I need to await the promise ...

Is there a way for me to set up a confirmation pop-up alert before hitting the submit

I am interested in implementing a pop-up alert that asks "Are you sure you want to delete this comment?" when a user clicks on a button. How can I achieve this? $('button').on('click', function(){ // Display an alert to the user c ...

Ensuring the model accurately reflects the input's value attribute in AngularJS

I am in the process of creating a set of image "radio buttons" where only one can be selected per group. However, as a newcomer to Angular, I'm facing difficulties in maintaining the value and using it as my ng-model. Additionally, I am looking for a ...

During initialization, React/Redux reducer produced an undefined value

Recently, I started working on my debut React/Redux project. Initially, everything was smooth sailing until I decided to implement a new reducer. The process seemed straightforward, but upon loading the page, an error popped up stating "Reducer X returned ...

What is the best way to utilize the "map" function in React to convert an array of objects into a different array of objects?

I need some help with React version 16.10.0. How can I change my array into a new array of objects? My original array consists of objects with the following attributes id name But now, I want to create a new array that contains objects with these attribu ...

Ensure the validation of multiple form fields in a single function

I've implemented code to validate a form field as you input values, changing the border color to red if invalid or green if valid: function FormValidation(){ var fn=document.getElementById("firstName").value; if(fn == ""){ document.ge ...

My findOne() function seems to be malfunctioning - could there be an issue with my syntax?

I have created a database called 'rodrigo-contatos' using the following code: var mongojs = require('mongojs'); var db = mongojs('rodrigo-contatos', ['rodrigo-contatos']); In an attempt to search the database, I am ...

What are some effective methods for troubleshooting unidentified JavaScript functions within Chrome's performance analyzer?

Currently, I am utilizing Angular 4 and incorporating numerous anonymous arrow functions (() => {}). I am curious if it is feasible to identify these functions in Chrome's performance analyzer without assigning them names. Below is an example of t ...

Compressed search bar when in mobile mode

My search bar is getting squashed on mobile devices. Any suggestions for fixing this issue? <div id="menu" class="py-4 d-flex justify-content-center"> <div class="row "> <div class="col-sm-auto "> ...

The art of encapsulating JSON response objects in Ember Objects with a deep layer of wrapping

Currently, I am engaged in a project using Ember where I retrieve a complex JSON response in a Route's model function. In the associated template, I exhibit attributes of the response. Some of these attributes allow for specific actions that result in ...

Numerous sections with tabs on the webpage

I am in need of incorporating multiple tabbed sections on a single page, but unfortunately they are currently interconnected. When one tab is clicked, it impacts the others. To see this issue in action, you can visit: https://jsfiddle.net/pxpsvoc6/ This ...

Creating a Vue.js component that animates text to fade in and out within a textarea when a button

I need assistance with updating a <textarea> element in my Vue application. Currently, I have the textarea bound to some data in my state. However, when a button is clicked, I want the existing data in the textarea to fade out and be replaced with ne ...

Looping through data in Vue.js with a specific condition

There is an object structured like this: groupedContacts: { 4: [ {name: 'foo'}, {name: 'bar'} ], 6: [ {name: 'foo bar'}, ] } Additionally, we have another array: companyList.models: models: [ ...

Fancybox fails to acknowledge the thumbs feature

I received a sneak peek of five thumbnails for a gallery, but the actual gallery contains even more photos. To prevent cluttering my code, I decided to store them in an array. Here is the snippet of HTML code: <div id="start_slides"> <a href ...

Unable to assign to 'disabled' as it is not recognized as a valid attribute for 'app-button'

How to link the disabled property with my button component? I attempted to add 'disabled' to the HTML file where it should be recognized as an input in the button component (similar to how color and font color are recognized as inputs) ... but ...