When the user is actively scrolling in the browser, the button will disappear. However, once the scrolling action is completed, the button will gradually fade

Is there a way to hide the button with the id #stats while the user is scrolling, and then have it fade back in once they finish scrolling?

It seems like the code below is not working as expected.

Any help would be greatly appreciated!

<button id="stats">
    <span class="icon prs">&#59146;</span><h3 id="views" class="prm">@file.views</h3>
    <span class="icon prs">&#59160;</span><h3 id="comments">20</h3>       
</button><!--end stats-->


<script>
    $(function(){  
        $('#stats').hide().fadeIn('slow');
    });

    var $stats = $("#stats");
    var opacity = $stats.css("opacity");
    var scrollStopped;

    var fadeInCallback = function () {
        if (typeof scrollStopped != 'undefined') {
            clearInterval(scrollStopped);
        }

        scrollStopped = setTimeout(function () {
            $stats.animate({ opacity: 1 }, "slow");
        }, 200);
    };

    $(window).scroll(function () {
        if (!$stats.is(":animated") && opacity == 1) {
            $stats.animate({ opacity: 0 }, "slow", fadeInCallback);
        } else {
            fadeInCallback.call(this);
        }
    });
</script>

Answer №1

In an effort to streamline it, I would suggest simplifying it to the following:

$(function(){
    var stats = $('#stats'),
        vis   = true;
        timer;


    stats.hide().fadeIn('slow');
    $(window).on('scroll', function() {
        clearTimeout(timer);
        if (vis) {
            stats.stop(true,true).fadeOut('slow');
            vis = false;
        }
        timer = setTimeout(function() {
            stats.stop(true,true).fadeIn('slow');
            vis = true;
        }, 400);
    });
});

FIDDLE

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

When utilizing CKEDITOR, the default TEXTAREA is obscured, and CKEDITOR does not appear

I am trying to incorporate CKEDITOR into my project. I have added the ckeditor script in the footer and replaced all instances of it. <script src="<?= site_url('theme/black/assets/plugins/ckeditor/ckeditor.min.js') ?>" type="text/javasc ...

Choose all elements by their class except for a particular container defined by the parent element's ID

Can you provide an example of translating the function below into utilizing the .not method (or not selector)? $(".CLASS").filter(function(i, e){ return (e.parentNode.id != "ID"); } ...

Troubleshooting Parallax Logic in NextJS

import Head from 'next/head' import styles from '../styles/Home.module.css' import Image from 'next/image' import React, { useRef ,useEffect, useState } from 'react'; export default function Home() { let ref = use ...

Will the useEffect hook re-run whenever the component renders if it includes props in its dependency array?

According to the React documentation on useEffect, it is recommended to include props in the dependency array of useEffect: import { useEffect } from 'react'; import { createConnection } from './chat.js'; function ChatRoom({ roomId }) ...

Verify if the header value corresponds

How can I validate the header value in a Node.js application? I want to restrict access to a certain route only if the user includes a specific header and its value matches what is expected. For instance, let's say the route requires a header like Acc ...

Converting Cyrillic characters to ASCII codes using JavaScript: A step-by-step guide

Is there a reliable method to convert characters from the CP1251 table to ASCII codes ranging from 0 to 255? So far, I have only come across the charCodeAt() function which is limited to codes up to 128. It returns a Unicode number for codes above that r ...

Is there a way to smoothly navigate back to the top within a Modal component while using React?

Here is the code snippet for scrolling back to the top of the page. const ScrollToTop = () => { const [showTopButton, setShowTopButton] = useState(false); useEffect(() => { window.addEventListener("scroll", () => { if ( ...

Retrieving registered components dynamically in Vue.js

Check out my scenario on jsBin In my setup, I have a selector <component :is="selectedComponent"></component>, along with a <select v-model="currentComponent">...</select> that allows me to choose which one is displayed. Currently ...

A guide on using FileReader to efficiently read multiple images

I need to be able to select multiple images from one input and read them using File Reader. If I leave it as is, it only gives me one picture. const [image , setImage] = useState(''); const [imageSelected , setImageSelected] = useState(nul ...

What's up with portable devices requiring two taps to hover over one DIV and affect another DIV?

Upon implementing "hover one DIV - affecting another inner DIV," a strange issue arose on iPad/iPhones where it now requires two taps to click on the link within the DIV with the hover effect: Below is the HTML code: <div class="portfblock"> &l ...

Determine whether the color is a string ('white' === color? // true, 'bright white gold' === color? // false)

I am facing an issue with multiple color strings retrieved from the database. Each color string needs to be converted to lowercase and then passed as inline styles: const colorPickerItem = color => ( <View style={{backgroundColor: color.toLowerC ...

Exploring the array mapping technique in React with nested objects

As part of a school project, I am working on creating a dashboard to visualize some data. I have successfully loaded the data into the front end using React. Now my goal is to retrieve specific values from a large array. However, I am uncertain about how ...

Changing an Array into JSON format using AngularJS

I am attempting to switch from a dropdown to a multiselect dropdown. <select name="molecularMethod" class="form-control" ng-model="request.molecularMethod" multiple> It is functioning properly. However, when items are selected, it generates an arra ...

How to show table cell value in Angular 4 using condition-based logic

I am a beginner in Angular development. Here is the HTML code I am working with: <tr *ngFor="let item of calendarTableSelected; let idx = index"> <span *ngIf="idx === 0"> <td style="width:15%;" *ngFor="let name of item.results" ...

Windows npm configuration settings

After receiving helpful answers to my previous question about using a named parameter in an npm run script, I encountered a new problem. It seems that the $npm_config_variable doesn't function correctly on Windows OS. I am in search of a solution that ...

The ng-click functionality seems to be malfunctioning when used within the controller in conjunction with ng-bind

After coding, I noticed that my ng-click function is not working. When I inspected the element, I couldn't find ng-click displayed anywhere. Can someone please help me figure out what I'm doing wrong? var app = angular.module('myApp' ...

Testing React Component State Updates

I've been dedicated to achieving close to 100% unit test coverage with my React application, focusing particularly on the useAsync hook. I came across a code snippet from react hooks: import { useState, useEffect, useCallback } from 'react'; ...

Building an array from scratch in Angular

Below is the URL to access the code: https://stackblitz.com/edit/ng-zorro-antd-start-xz4c93 Inquiring about creating a new array. For example, upon clicking the submit button, the desired output should resemble the following structure: "tasks": [ { ...

Tips on how to dynamically load the content of a URL into a modal and update the browser address simultaneously

I am attempting to achieve a specific effect using JavaScript and jQuery Link to the content I want to load in a modal The goal is to load the content in a modal while keeping the main page in the background. Additionally, when a URL is followed, I want ...

Modifying the maxHeight property of the angular-gantt component does not yield any noticeable changes

I am currently experiencing issues with dynamically changing the height using the angular-gantt library. Despite setting a new value for the maxHeight attribute in the controller, it does not reflect on the view as expected. I have seen this feature work i ...