Using jQuery to create a div that animates when scrolling

Recently, I came across this interesting code snippet:

$(document).ready(function(){
$(window).scroll(function(){
   if($("#1").offset().top < $(window).scrollTop());
    $("#1").animate({"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"}, 1000);
}, function() {
$("#1").animate({"color":"#333","font-size":"52pt", "top":"0", "position":"fixed"}, 1000);
  });
});

I found it on jsfiddle. It's quite intriguing to see how the text animates when scrolling. However, I would like to know how to make the text return to its original state once it reaches the top of the content again.

If anyone has any insights or solutions to this, I would greatly appreciate it. Thank you in advance!

Best regards

Answer №1

When it comes to browser support, what are your requirements? Animating back can be tricky since the original style needs to be known.

One approach is using the window.getComputedStyle method to fetch the element's styles and store them in an object array for animating back. Additional supporting functions may be necessary.

I have tested the code below in Chrome, IE 9, and FireFox 24 with satisfactory results. The effectiveness may vary based on the styles being used. However, it should generally work well for animations.

The styles and speed have been stored in variables for better organization. Check out the fiddle below:

$(document).ready(function(){
    var aniCss = {"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"};
    var speed = 1000;
    var props = getProps(aniCss);
    var curCss = getStyles($("#1"), props);
    $(window).scroll(function(){
        if ($(window).scrollTop() >0) {
            $("#1").animate(aniCss,speed);
        }
        else {
            $("#1").stop(true,true).animate(curCss,speed);
        }
    });

    function getProps(css) {
        var props = [];
        for (k in css) {
            props.push(k);
        }
        return props;
    }
    function getStyles($ele, props) {
        var compCss = getComputedStyle($ele[0]);
        var styles = {};
        for (var i = 0;i<props.length;i++) {
            var name = props[i];
            var prop = compCss.getPropertyValue(name);
            if (prop != '') { styles[name]=prop;}
        }
        return styles;
    }
});

Fiddle: http://jsfiddle.net/ajqQL/1/

Update: jQuery 1.9 introduced the ability to pass an array of properties to retrieve values. You can simplify the above code by utilizing the jQuery .css() method:

$(document).ready(function(){
    var aniCss = {"color":"#efbe5c","font-size":"52pt", "top":"0", "position":"fixed"};
    var speed = 400;
    var props = getProps(aniCss);
    var curCss = $('#1').css(props);
    $(window).scroll(function(){
        if ($(window).scrollTop() >0) {
            $("#1").animate(aniCss,speed);
        }
        else {
            $("#1").stop(true,true).animate(curCss,speed);
        }
    });

    function getProps(css) {
        var props = [];
        for (k in css) {
            props.push(k);
        }
        return props;
    }
});

Fiddle: http://jsfiddle.net/NZq8D/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

AJAX: Displaying the contents of a folder. Issue with URL resolution

I'm attempting to showcase a collection of images stored in a specific folder within a div. My approach involves utilizing AJAX within a JavaScript file titled edit, which is positioned one directory away from the index route. This implementation is b ...

How can I assign integer values to specific child elements after splitting them?

Below is the HTML code that needs modification: <div class="alm-filter alm-filter--meta" id="alm-filter-1" data-key="meta" data-fieldtype="checkbox" data-meta-key="Cate" data-meta-compare="IN" data-meta-type="CHAR"> <ul> <li class=" ...

How can you make the contents of a <DIV> expand?

Picture a scenario where I have a navigation bar in the header of my web page, consisting of several links. What I want is for these links to expand horizontally to fill the parent container without me having to hard-code based on the number of links. In o ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

I'm having trouble anchoring my images to a specific spot on the webpage in HTML

After creating my divs in css and linking them to my index file, I encountered an issue when zooming out of the page. The images would shift to the left while the background remained centered. I needed help figuring out how to keep an image fixed on the pa ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

The separator falls short of spanning the entire width of the page

For some reason, I can't seem to make the divider extend to the full length of the page. <TableRow> <TableCell className={classes.tableCell} colSpan={6}> <Box display="grid" gridTemplateColumn ...

Creating a vertical triangle pointing to the right as the border of a div element

Currently, I'm working on a mockup that includes the following elements. I am attempting to ensure that the triangular right end of the "Delay Your Payments" div matches the mockup exactly. To achieve this, I aim to use CSS without relying on sliced ...

Struggles with CSS hover effects on text and buttons

Beginner in the world of HTML & CSS Struggling with the following: Hover Effect: Looking to implement a hover effect where hovering over either the staff name text or the circle button above it triggers the appearance of a square border (refer to 'A ...

Animating background images using a single data attribute

I'm attempting to create a smooth animation between different background images stored in a single data attribute. The goal is for each image to load sequentially, with the first one appearing immediately and the rest following after a 5-second delay. ...

Working with jQuery: Creating multiple lightboxes using the same jQuery code

Is there a way to create a universal lightbox with the same code for all lightbox functions on the page using JQuery? $(document).ready(function() { $('.lightbox').click(function() { $('.backdrop, .box').animat ...

Troubleshooting Problem with Centering Rows in Bootstrap

I am utilizing the most recent version of Bootstrap 3 to design a website for a friend, but I am encountering a challenge with centering elements on the page. Typically, I would use the following code: .center{ width: 90%; margin: 0 auto; } Howev ...

PHP-generated interactive pie chart

I'm encountering a puzzling issue while attempting to create a pie chart in Flot using data from PHP. The chart seems to be rendering incorrectly, and I'm struggling to identify the cause. Below is my PHP code (used for testing): echo json_enc ...

When pasting Arabic text into an input box, the words in HTML appear to be jumbled and shuffled around

When I replicate this text يف عام and input it into a box, the output is shown as follows عام يف ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Overriding Divs with Navigation

In my WordPress blog, the top menu consists of 3 divs: one for navigation, one for social icons, and one for the search bar. Unfortunately, the navigation div is currently overriding the other two divs, causing them to lose their functionality. When I ad ...

Setting a minimum time in the Bootstrap DateTimePicker widget

I am facing an issue with my bootstrap datetimepicker. Currently, the minimum time allowed is set to real-time, but I need it to be real-time plus 20 minutes. For example, if the current time is 2:30 PM, I want the minimum time allowed in the datetimepic ...

Passing a parameter from AJAX to PHP

const studentNumber = $('#studno').val(); $(document).ready(function () { $('.go').click(function () { $('.inup').load('prochat.php', { studno: studentNumber }); }); }); I've ...

Implementing a persistent header on a WordPress site with Beaver Builder

My website URL is: . I have chosen to use beaver builder for building and designing my website. I am in need of a fixed header that can display over the top of the header image. Here is the code snippet that I currently have: <div id="header">html ...

Initiate the timer in JQuery

function begin() { rMinutes = Math.floor((Math.random() * 1) + 1); rSeconds = Math.floor((Math.random() * 59) + 1); $('#minutes').text(rMinutes); $('#seconds').text(rSeconds); int1 = setInterval(function timer() { i ...