JavaScript: create a button that dynamically changes size and color when scrolling

I have a pulsing button (#scrollarrow) at the bottom of my website that disappears as I start scrolling. The jQuery code responsible for this effect is as follows:

$(document).ready(function(){

$(window).scroll(function(){              
        if ($(this).scrollTop() > 50) {
            $('#scrollarrow').fadeOut('slow');
        }else{
            $('#scrollarrow').fadeIn('slow');
        } 
    }); 
});

Everything works fine up to this point. However, when I try to add a pulse effect (a simple change of opacity), things get tricky:

function pulse(){
    $('#scrollarrow').delay(200).fadeOut('slow').delay(50).fadeIn('slow',pulse);
}

The problem arises when trying to integrate this function into the existing code. The result I achieve is seeing the button pulse after scrolling, which is the opposite of what I intended. Despite attempting various combinations, none seem to provide the desired outcome.

If anyone has any suggestions or solutions, please share them with me. Thank you!

Answer №1

If you're looking to make the arrow pulse before the user starts scrolling, you can achieve it by following this approach: http://jsfiddle.net/P99Ey/28/

$(document).ready(function(){
    // Function to animate the button and repeat itself after completion
    function pulse() {
        if ($(window).scrollTop() <= 50) {
            $('#scrollarrow').delay(200).fadeOut('slow').delay(50).fadeIn('slow', pulse);
        }
    }

    pulse();

    $(window).scroll(function(){              
        if ($(this).scrollTop() > 50) {
            $('#scrollarrow').clearQueue();
            $('#scrollarrow').fadeOut("slow");
        } else{
            pulse();
        } 
    }); 
});

Answer №2

If you're interested, take a look at CSS3 Animations. This allows you to create keyframes for pulsing buttons without needing JavaScript. Although browser support might not be as extensive with CSS3, there are performance advantages in letting the browser handle animations. Additionally, CSS3 animations will work even when JavaScript is disabled.

Answer №3

Here is a helpful solution for you:

HTML Code

<div id="scrollarrow">Test</div>

CSS Styling

#scrollarrow
{
    position:fixed;
}

JQuery Implementation

$(function () {
    function trigger_animation($element, delay, duration) {
        $element.delay(delay).fadeToggle(duration, function () {
            trigger_animation($element, delay, duration);
        });
    }
    trigger_animation($('#scrollarrow'), 100, 50);
});

 $(window).scroll(function(){              
        if ($(this).scrollTop() > 50) {
            $('#scrollarrow').fadeOut('slow');
        }else{
            $('#scrollarrow').fadeIn('slow');
            // This code snippet will restart the animation when the user scrolls back to the top of the page
            pulse();
        } 
    }); 

Demo Link: Check out the live demo here!

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

How can TailwindCSS be used to wrap a nested flexbox at a specific viewport?

Utilizing TailwindCSS, I have the following code snippet: <div class="box-border flex w-auto flex-row gap-2 rounded-2xl border p-4 my-4 mx-4"> <div class="grow-0"> <div class="flex h-full flex-col items-center ...

"Utilize the parent component's functionality by extending/inheriting it

export default function PageTemplate() { return ( <div className="layout"> <LeftMenu /> <div className="content"> <TopMenu /> <div id="other-contents"> ...

Instagram API: Retrieving a list of recently tagged media only displays content that belongs to me

Is there a way to retrieve all recently tagged media from all users, similar to what is shown on this link ? The Instagram API only provides media from the access_token's owner. Once again: requestUrl = 'https://api.instagram.com/v1/tags/&apo ...

A guide on adding specific rows together in a list

I'm working with a grid that contains various items and I want to calculate the total of the val_itemservico column only for the selected rows, not all of them. How can I achieve this functionality? When the user clicks on the "Calculate" button, I n ...

Attempting to extract only the text content from a specific div using XPath

I am currently facing a challenge in writing a script to extract the title element from a poorly coded webpage. The developer who created this website did not use any classes, only div elements. Below is a snippet of the source code I am trying to scrape: ...

AngularJS $http.post() response function not executing in the correct sequence

When calling a function from my angular controller to make a $http.post() request, the code below the function call is executing before the successFunction(), preventing the code inside the if block from running. How can I ensure the if block executes wi ...

Issue with text input field causing the Enter key to not create a new line

In the example above, the text is placed in the middle of the text area. Here is the CSS code : .form-control { height: 300px; display: block; width: 100%; padding: 0.375rem 0.75rem; font-size: 1rem; font-weight: 400; line-heig ...

Create a string that has been properly formatted

I need a javascript alternative to the StringEscapeUtils in java, specifically for converting input strings like: He didn't say, "Stop!" The desired output format should be: He didn't say, \"Stop!\" Is there a similar function a ...

Using jQuery to separate a JSON array that has been retrieved from PHP

I am just starting to learn about JQuery and the entire process of communicating between JQuery and PHP. Here is a basic ajax JQuery script that I have: $.ajax({ type: "POST", url: "includes/calc.php", data: { ...

Leverage ng-value attribute when working with radio buttons in AngularJS

I have recently started working with AngularJS and I am trying to create a selection using radio buttons that will save as a boolean value. However, when I use ng-value, the value saved in the database is null. Here is the HTML code: <label><in ...

"Exploring the Mini Drawer feature on Material UI brings up a whole new page for the Link

Currently, I am working on a project that involves updating stocks using Material UI. I have implemented a mini drawer from Material UI, but when I click on the menu link, it routes to a new page instead of rendering on the homepage itself. In my App.JS f ...

Determine the mean values to showcase at the center of a D3 donut graph

Check out this plunkr where I'm utilizing angularjs and d3.js. In the plunkr, I've created several donut charts. I'm interested in learning how to display the average data in the center of the arc instead of the percentage. Additionally, I& ...

What causes let to lose significance within the context of React development?

In my React code snippet, I am encountering an issue with the organizationId variable. Even though I can see its value in the first and second instances, I am unable to see it in the third instance. This strange behavior is occurring in a Next.js based pro ...

Adjust the size of an image within a container in real-time with jQuery

In my coding project, I have a div element called "content_container" that is designed to be draggable and resizable using jQuery UI. Within this container, I have integrated TinyMCE, a content text editor. My current challenge involves the scenario where ...

Is there a way I can retrieve a cookie stored in an Express middleware even if the req.cookies object is returning empty?

I am currently working on validating a cookie using the cookie-parser module to verify if the user is authenticated to access restricted routes within my application. My technology stack includes NodeJS and Express for the server, and Sveltekit for the fro ...

`Locating an image alongside text for seamless integration`

Take a moment to view the image displayed below Feature 1 and feature 4 are two distinct divs that I have styled with the Bootstrap class .col-md-4 Here is the corresponding HTML code <div class="col-md-4"> <div class="feature-group-1"> ...

React Application Issue 'Error: React is not defined'

I've been working on developing an app using react, but for some reason, it's not functioning properly and I'm struggling to pinpoint the issue. The code compiles without errors using babelify, however, it throws an exception during executio ...

What is the method for transforming an array object into an object?

How can I assign the values of an array object called hello to a constant called answer, changing the key value in the process? I've considered using Object.entries but couldn't quite get it right. Is there a way to achieve this? Here is my cod ...

jQuery removes HTML tags from XML documents

I currently have a setup where a page is functioning as an AJAX loader with the help of jQuery. It is designed to retrieve XML documents, like the one shown below, and then place the values of title, authPhrase, and content into the appropriate div element ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...