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

I am having trouble creating a modal box for my gallery images

I'm currently working on a PHP dynamic site and I've encountered an issue with my gallery code. For some reason, the modal box is not showing up when I click on the gallery images. Can anyone please assist me in resolving this problem? var mod ...

Angular 5.2: Component type does not contain the specified property

In my Formbuilder.Group method, I have included the properties as shown in the following TypeScript code: this.form = this.fb.group({ caseNumber: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(50), Val ...

Inconsistent Animation Issue with jQuery Toggle for Expanding Div and Text

My expanding div functionality is almost perfect, but I've noticed that the transition when opening abruptly on divs with text. However, the closing transition is smooth. Can anyone help me make the opening transition as smooth as the closing one? Bel ...

Guidelines for transferring data when a button is held down or pressed

I am looking to continuously send values while a button is pressed. Currently, a value is only sent with each click. Below is the current code: my_custom_script.js $(document).ready(function() { $('#left').mousedown(function() { var left ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

Efficiently Fill JQUERY Mobile Multi-Pages with Dynamic Content

A Question for JQUERY Mobile Beginners: In my basic JQUERY Mobile application, I have a simple setup with two pages. When the user navigates to PAGE2, I need to make an AJAX call to retrieve a JSON object that contains a list of people along with their DB ...

Replacing defined WordPress CSS styles

I was considering posting this query on the Wordpress Stack Exchange platform, but it's more related to CSS than Wordpress. Unless I need to delve into the CSS files of a plugin to customize the styles, should I go there to ask this question? I am t ...

One blade is successfully utilizing the AJAX URL, while the other blade is experiencing difficulties with it

I have successfully implemented AJAX in Laravel to fetch data from a database. The code for my AJAX call is as follows: $('#salesmanlist_input').on('change', function() { var salesmanlist_input = $(this).val(); ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

How can I make my JQuery datatable span the full width of the screen, regardless of the resolution?

In my Rails application, I am using JQuery Datatable with the following code: <%= content_tag :table, role: :my_datatable, id: 'my_datatable', style: 'height:500px; overflow-y: auto;&apo ...

Using AJAX and Jquery to stop the page from reloading when a button is clicked

I am currently working on a gridview that displays all transactions of a merchant, including pending, approved, and rejected transactions. The gridview is set up with template and includes two buttons. My goal is to prevent the page from reloading when one ...

Creating a horizontal line with text centered using Angular Material's approach

Implementing Angular Material, my objective is to design a horizontal line with a word positioned in the center. Similar to the one showcased here. I experimented with this code, achieving a close result, but I aim to align the lines vertically to the mid ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...

What is the process for obtaining the hash of every hyperlink?

I'm currently working on implementing an active link state based on scroll position for each section. My goal is to extract the hash value from the link. The issue I'm facing is that when I run the line 'console.log($(this).eq(i).hash);&ap ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Step-by-step guide on making a duplicate of a Search bar

I have a search field in my application that I want to duplicate. The goal is to create two identical search fields, one on the left side of the page and another on the right side. How can I achieve this using JavaScript? Here is my JavaScript code: doc ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

The alignment of elements in the div seems to be slightly skewed

Currently, I am in the process of creating a website with the temporary name yeet.io. I am facing an issue where I am attempting to center both an input and h1 element inside a div vertically and horizontally, but they keep appearing misaligned for some r ...

Adjust the size of the div to match its parent's size when resizing

Can a div be resized to match its parent's size on window resize? Here is the current HTML code: <div class="sliderContainer"> <div id="cyler"> <div class="cy1" style="background-image:url(images/Keggy_Banner_Ie.jpg); back ...

Localized Error: The property 'clientWidth' cannot be retrieved as the object is null or undefined

The issue with the error message seems to only occur on Internet Explorer, and unfortunately there doesn't seem to be a clear solution at the moment. Even after setting http-equiv="X-UA-Compatible" to IE8, the problem persists and I cannot seem to re ...