jQuery - Scrolling

jquery

https://www.sitepoint.com/animations-using-easings-to-craft-smarter-interactions/
https://www.sitepoint.com/our-top-9-animation-libraries/

https://www.sitepoint.com/guide-jquery-animate-method/
https://www.sitepoint.com/introduction-jquery-scroll-based-animations/
https://www.abeautifulsite.net/smoothly-scroll-to-an-element-without-a-jquery-plugin-2
https://howchoo.com/g/yjfjmty1zjb/how-to-animate-scroll-in-jquery - done reading
http://api.jquery.com/scroll/ - done reading
http://api.jquery.com/animate/ - done reading
https://jqueryui.com/animate/ - done reading
http://www.learningjquery.com/2009/02/quick-tip-add-easing-to-your-animations - done reading
https://web-design-weekly.com/snippets/scroll-to-position-with-jquery/ - done reading
https://paulund.co.uk/how-to-create-an-animated-scroll-to-top-with-jquery - done reading

What is the purpose of jQuery's .scroll function?

It is used to bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. It's signatures:

.scroll( function(eventObject) { ... } );  // Register a handler for the scroll event
.scroll( [eventData ], function(eventObject) { ... } ); // eventData can be anything
.scroll(); // Trigger the scroll event handler.

This method is a shortcut for .on( "scroll", handler ) or .trigger( "scroll" ).

The scroll event is sent to an element when the user scrolls to a different place in the element. It applies to window objects, but also to scrollable frames and elements with the overflow CSS property set to scroll (or auto when the element's explicit height or width is less than the height or width of its contents).

$( "#target" ).scroll(function(eventObject) {
  ...
});

To trigger the event manually, apply .scroll() without an argument:

$( "#other" ).click(function() {
  $( "#target" ).scroll();
});

A scroll event is sent whenever the element's scroll position changes, regardless of the cause. A mouse click or drag on the scroll bar, dragging inside the element, pressing the arrow keys, or using the mouse's scroll wheel could cause this event.

As the .scroll() method is just a shorthand for .on( "scroll", handler ), detaching is possible using .off( "scroll" ).

What are the signatures of the jQuery's .animate function?

.animate( properties [, duration ] [, easing ] [, complete ] )
.animate( properties, options )
  1. properties: (plain object). An object of CSS properties and values that the animation will move toward.
  2. duration: (Number or String, default: 400). A string or number determining how long the animation will run.
  3. easing: (String, default: 'swing'). A string indicating which easing function to use for the transition.
  4. complete: (Function). A function to call once the animation is complete, called once per matched element.
  5. options: (plain object). A map of additional options to pass to the method.
    1. duration: (Number or String, default: 400). A string or number determining how long the animation will run.
    2. easing: (String, default: 'swing'). A string indicating which easing function to use for the transition.
    3. queue: (Boolean or String, default: true). A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it.
    4. specialEasing: (plain object). An object containing one or more of the CSS properties defined by the properties argument and their corresponding easing functions.
    5. step: (Function( Number now, Tween tween )). A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set.
    6. progress: (Function( Promise animation, Number progress, Number remainingMs )). A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties
    7. complete: (Function). A function that is called once the animation on an element is complete.
    8. start: (Function( Promise animation )). A function to call when the animation on an element begins.
    9. done: (Function( Promise animation, Boolean jumpedToEnd )). A function to be called when the animation on an element completes (its Promise object is resolved).
    10. fail: (Function( Promise animation, Boolean jumpedToEnd )). A function to be called when the animation on an element fails to complete (its Promise object is rejected)
    11. always: (Function( Promise animation, Boolean jumpedToEnd )). A function to be called when the animation on an element completes or stops without completing (its Promise object is either resolved or rejected).

What can we do with the .animate method?

The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a plain object of CSS properties. This object is similar to the one that can be sent to the .css() method, except that the range of properties is more restrictive.

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

In addition to style properties, some non-style properties such as scrollTop and scrollLeft, as well as custom properties, can be animated.

Shorthand CSS properties (e.g. font, background, border) are not fully supported. For example, if you want to animate the rendered border width, at least a border style and border width other than "auto" must be set in advance. Or, if you want to animate font size, you would use fontSize or the CSS equivalent 'font-size' rather than simply 'font'.

In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element. In order to use jQuery's built-in toggle state tracking, the 'toggle' keyword must be consistently given as the value of the property being animated.

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

Unlike shorthand animation methods such as .slideDown() and .fadeIn(), the .animate() method does not make hidden elements visible as part of the effect. For example, given $( "someElement" ).hide().animate({height: "20px"}, 500), the animation will run, but the element will remain hidden.

How are the callback methods invoked by the .animate() method?

If supplied, the start, step, progress, complete, done, fail, and always callbacks are called on a per-element basis; this is set to the DOM element being animated. If no elements are in the set, no callbacks are called. If multiple elements are animated, the callback is executed once per matched element, not once for the animation as a whole. Use the .promise() method to obtain a promise to which you can attach callbacks that fire once for an animated set of any size, including zero elements.

How can we animate the opacity, left offset, and height of the image simultaneously?

To animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123"
  style="position: relative; left: 10px;">
$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });
});

Note that the target value of the height property is 'toggle'. Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition.

The object that contains the "meta" CSS properties specify the "destination" states. The starting state is automatically determined from the element.

The opacity of the image is already at its target value, so this property is not animated by the second click. Since the target value for left is a relative value, the image moves even farther to the right during this second animation.

Does the directional properties (top, right, bottom, left) have any discernible effect on elements if their position style property is static?

No. Directional properties (top, right, bottom, left) have no discernible effect on elements if their position style property is static, which it is by default.

What does the jQuery UI project do for the .animate() method?

The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.

What does jQuery animate do when attempting to animate an element with a height or width of 0px?

If attempting to animate an element with a height or width of 0px, where contents of the element are visible due to overflow, jQuery may clip this overflow during animation. By fixing the dimensions of the original element being hidden however, it is possible to ensure that the animation runs smoothly. A clearfix can be used to automatically fix the dimensions of your main element without the need to set this manually.

What are some examples of using .animate()?

$( "#go" ).click(function() {
  $( "#block" ).animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );
});
$( "#right" ).click(function() {
  $( ".block" ).animate({ "left": "+=50px" }, "slow" );
});

$( "#left" ).click(function(){
  $( ".block" ).animate({ "left": "-=50px" }, "slow" );
});
$( "#go1" ).click(function() {
  $( "#block1" )
    .animate({
      width: "90%"
    }, {
      queue: false,
      duration: 3000
    })
    .animate({ fontSize: "24px" }, 1500 )
    .animate({ borderRightWidth: "15px" }, 1500 );
});

$( "#go2" ).click(function() {
  $( "#block2" )
    .animate({ width: "90%" }, 1000 )
    .animate({ fontSize: "24px" }, 1000 )
    .animate({ borderLeftWidth: "15px" }, 1000 );
});

$( "#go3" ).click(function() {
  $( "#go1" ).add( "#go2" ).click();
});

$( "#go4" ).click(function() {
  $( "div" ).css({
    width: "",
    fontSize: "",
    borderWidth: ""
  });
});
$( "#go" ).click(function() {
  $( ".block:first" ).animate({
    left: 100
  }, {
    duration: 1000,
    step: function( now, fx ){
      $( ".block:gt(0)" ).css( "left", now );
    }
  });
});
$( "p" ).animate({
  height: "toggle",
  opacity: "toggle"
}, "slow" );
$( "p" ).animate({
  left: 50,
  opacity: 1
}, 500 );
$( "p" ).animate({
  left: "50px",
  opacity: 1
}, {
  duration: 500,
  queue: false
});

An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden.

$( "p" ).animate({
  opacity: "show"
}, "slow", "easein" );
$( "p" ).animate({
  height: "toggle",
  opacity: "toggle"
}, {
  duration: "slow"
});
$( "p" ).animate({
  opacity: "show"
}, {
  duration: "slow",
  easing: "easein"
});
$( "p" ).animate({
  height: 200,
  width: 400,
  opacity: 0.5
}, 1000, "linear", function() {
  alert( "all done" );
});

How can we animate scrolling to the bottom of the page?

$('html, body').animate({scrollTop : document.body.scrollHeight},800);

How can we animate scrolling to the top of the page?

$('html, body').animate({scrollTop : 0},800);

What is the purpose of the .fadeIn() method?

Obviously, it is used to fade the element in to visible.

$('.scrollToTop').fadeIn();

What is the purpose of the .fadeOut method?

Obviously, it is used to fade out the element so that it becomes not visible.

$('.scrollToTop').fadeOut();

How can we animate colors?

jQuery UI bundles the jQuery Color plugins which provides color animations as well as many utility functions for working with colors. Want to learn more about color animations? Check out the jQuery Color documentation.

How can we use advance easing functions?

Easing controls how an animation progresses over time by manipulating its acceleration. jQuery has two built-in easing methods: linear and swing. While they get the job done, they are pretty boring when compared to what's made available through the jQuery easing plugin. The jQuery easing plugin offers 30 different easing methods, courtesy of Robert Penner's easing equations. Let's check some of them out.

Easing can only be applied when using the .animate() method. The effects helper methods like .show('fast'), .toggle('fast'), fadeIn('fast'), and so on all just use the default easing, "swing."

There are two ways to use easing with the .animate() method. For example, let's say we want to animate the opacity of a particular div. The first way to call .animate() is like this:

    $('#myDiv').animate(
        { opacity: 0 }, // what we are animating
        'fast', // how fast we are animating
        'swing', // the type of easing
        function() { // the callback
            alert('done');
        });

The second way is very similar and might even look the same at first glance.

    $('#myDiv').animate(
        { opacity: 0 }, // what we are animating
        {
            duration: 'fast', // how fast we are animating
            easing: 'swing', // the type of easing
            complete: function() { // the callback
                alert('done');
            }
        });

The difference is that the second method signature takes only two arguments: the properties we are animating and an object literal of settings/options. The first method signature separates out the settings/options into individual arguments.

The available easing 'methods' are:

  1. easeOutBounce
  2. easeOutElastic
  3. easeOutBack
  4. More available. Check the documentation mention above.

jQuery UI includes the easing plugin as part of its Effects Core. It also extends the effects helper methods to support the use of easing and even other types of effects. You can find the documentation for jQuery UI Effects here.

How can we implement the 'scroll into view' method with animation?

$.fn.scrollView = function () {
  return this.each(function () {
    $('html, body').animate({
      scrollTop: $(this).offset().top
    }, 1000);
  });
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License