Articles

JQuery, how can we implement dynamic effects with JQuery

With JQuery you can create dynamic effects, animations and fades by acting on the elements of an HTML page.

In this article we will see how to use different JQuery methods for generating animations.

Hide and show an HTML element

Methods hide() And show()

The hide() method simply sets the style inline display: none for selected items. Conversely, the show() method restores the display properties. 

Let's see an example:

<script>
$(document).ready(function(){
    // Hide displayed paragraphs
    $(".hide-btn").click(function(){
        $("p").hide();
    });
    
    // Show hidden paragraphs
    $(".show-btn").click(function(){
        $("p").show();
    });
});
</script>

In the first case the paragraph is hidden when you click on the button (hide-btn), in the second case the paragraph is shown when you click on the button (show-btn).

You can also specify the duration parameter, to animate the show and hide effect for a period of time.

Durations can be specified using one of the pre stringsdefinight 'slow''fast', or in a number of milliseconds, for greater precision; higher values ​​indicate slower animations.

<script>
$(document).ready(function(){
    // Hide displayed paragraphs with different speeds
    $(".hide-btn").click(function(){
        $("p.normal").hide();
        $("p.fast").hide("fast");
        $("p.slow").hide("slow");
        $("p.very-fast").hide(50);
        $("p.very-slow").hide(2000);
    });
    
    // Show hidden paragraphs with different speeds
    $(".show-btn").click(function(){
        $("p.normal").show();
        $("p.fast").show("fast");
        $("p.slow").show("slow");
        $("p.very-fast").show(50);
        $("p.very-slow").show(2000);
    });
});
</script>

The string predefinita 'fast' indicates a duration of 200 milliseconds, while the string 'slow' indicates the duration of 600 milliseconds.

We can specify a function of callback to be executed after method completion show() or the ' hide()

<script>
$(document).ready(function(){
    // Display alert message after hiding paragraphs
    $(".hide-btn").click(function(){
        $("p").hide("slow", function(){
            // Code to be executed
            alert("The hide effect is completed.");
        });
    });
    
    // Display alert message after showing paragraphs
    $(".show-btn").click(function(){
        $("p").show("slow", function(){
            // Code to be executed
            alert("The show effect is completed.");
        });
    });
});
</script>
The toggle method

The jQuery method toggle() show or hide items in such a way that if the item is initially displayed, it will be hidden; conversely if hidden, it will be displayed (practically toggles its visibility).

<script>
$(document).ready(function(){
    // Toggles paragraphs display
    $(".toggle-btn").click(function(){
        $("p").toggle();
    });
});
</script>

Similarly, you can specify the parameter duration for the method toggle(), in such a way as to animate the transition between visible and hidden, like methods show() e hide()

<script>
$(document).ready(function(){
    // Toggles paragraphs with different speeds
    $(".toggle-btn").click(function(){
        $("p.normal").toggle();
        $("p.fast").toggle("fast");
        $("p.slow").toggle("slow");
        $("p.very-fast").toggle(50);
        $("p.very-slow").toggle(2000);
    });
});
</script>

Similarly, you can also specify a function of callback for the method toggle().

<script>
$(document).ready(function(){
    // Display alert message after toggling paragraphs
    $(".toggle-btn").click(function(){
        $("p").toggle(1000, function(){
            // Code to be executed
            alert("The toggle effect is completed.");
        });
    });
});
</script>

jQuery fade effects

Methods fadeIn()fadeOut()

You can use jQuery methods fadeIn()fadeOut() to show or hide HTML elements, gradually increasing or decreasing their opacity and creating a fading effect.

<script>
$(document).ready(function(){
    // Fading out displayed paragraphs
    $(".out-btn").click(function(){
        $("p").fadeOut();
    });
    
    // Fading in hidden paragraphs
    $(".in-btn").click(function(){
        $("p").fadeIn();
    });
});
</script>

Like other jQuery effects methods, you can optionally specify duration or speed parameter for methods fadeIn()fadeOut(), in order to control the duration of the fade. Durations can be specified using one of the pre stringsdefinight 'slow''fast', or in a number of milliseconds; higher values ​​indicate slower animations.

<script>
$(document).ready(function(){
    // Fading out displayed paragraphs with different speeds
    $(".out-btn").click(function(){
        $("p.normal").fadeOut();
        $("p.fast").fadeOut("fast");
        $("p.slow").fadeOut("slow");
        $("p.very-fast").fadeOut(50);
        $("p.very-slow").fadeOut(2000);
    });
    
    // Fading in hidden paragraphs with different speeds
    $(".in-btn").click(function(){
        $("p.normal").fadeIn();
        $("p.fast").fadeIn("fast");
        $("p.slow").fadeIn("slow");
        $("p.very-fast").fadeIn(50);
        $("p.very-slow").fadeIn(2000);
    });
});
</script>

the effect of the methods fadeIn()fadeOut() It is similar to show()hide(), but unlike the methods show()hide(), the former only animate the opacity of the target elements and do not animate their size.

Also you can specify a function of callback to run after the methods complete fadeIn()fadeOut().

<script>
$(document).ready(function(){
    // Display alert message after fading out paragraphs
    $(".out-btn").click(function(){
        $("p").fadeOut("slow", function(){
            // Code to be executed
            alert("The fade-out effect is completed.");
        });
    });
    
    // Display alert message after fading in paragraphs
    $(".in-btn").click(function(){
        $("p").fadeIn("slow", function(){
            // Code to be executed
            alert("The fade-in effect is completed.");
        });
    });
});
</script>
Method fadeToggle()

The jQuery method fadeToggle() displays or hides selected elements by animating their opacity such that if the element is initially displayed, it will be faded out; if it was hidden, it will fade out (i.e. toggle the fade effect).

<script>
$(document).ready(function(){
    // Toggles paragraphs display with fading
    $(".toggle-btn").click(function(){
        $("p").fadeToggle();
    });
});
</script>

You can also specify the lifetime parameter for the method fadeToggle() as for the methods fadeIn()fadeOut(), to control the duration or speed of the fade animation.

<script>
$(document).ready(function(){
    // Fade Toggles paragraphs with different speeds
    $(".toggle-btn").click(function(){
        $("p.normal").fadeToggle();
        $("p.fast").fadeToggle("fast");
        $("p.slow").fadeToggle("slow");
        $("p.very-fast").fadeToggle(50);
        $("p.very-slow").fadeToggle(2000);
    });
});
</script>

The fadeToggle() method also has the ability to specify a function callback.

<script>
$(document).ready(function(){
    // Display alert message after fade toggling paragraphs
    $(".toggle-btn").click(function(){
        $("p").fadeToggle(1000, function(){
            // Code to be executed
            alert("The fade-toggle effect is completed.");
        });
    });
});
</script>
Method fadeTo()

The jQuery method fadeTo() it is similar to the method fadeIn(), but unlike the method fadeIn(), the method fadeTo() lets you blend elements down to a certain level of opacity.

$(selector).fadeTo(speed, opacity, callback);

The required parameter opacity specifies the final opacity of the target elements which can be a number between 0 and 1. The parameter duration o speed it is also required for this method which specifies the duration of the animation fade.

<script>
$(document).ready(function(){
    // Fade to paragraphs with different opacity
    $(".to-btn").click(function(){
        $("p.none").fadeTo("fast", 0);
        $("p.partial").fadeTo("slow", 0.5);
        $("p.complete").fadeTo(2000, 1);
    });
});
</script>

Scroll effects

Methods slideUp()slideDown()

The jQuery method slideUp()slideDown() are used to hide or show HTML elements by gradually decreasing or increasing their height (i.e. scrolling them up or down).

<script>
$(document).ready(function(){
    // Slide up displayed paragraphs
    $(".up-btn").click(function(){
        $("p").slideUp();
    });
    
    // Slide down hidden paragraphs
    $(".down-btn").click(function(){
        $("p").slideDown();
    });
});
</script>

Like other jQuery effects methods, you can optionally specify duration or speed parameter for the methods slideUp()slideDown() to control the duration of the slide animation. Durations can be specified using one of the pre stringsdefinight 'slow''fast', or in a number of milliseconds; higher values ​​indicate slower animations.

<script>
$(document).ready(function(){
    // Sliding up displayed paragraphs with different speeds
    $(".up-btn").click(function(){
        $("p.normal").slideUp();
        $("p.fast").slideUp("fast");
        $("p.slow").slideUp("slow");
        $("p.very-fast").slideUp(50);
        $("p.very-slow").slideUp(2000);
    });
    
    // Sliding down hidden paragraphs with different speeds
    $(".down-btn").click(function(){
        $("p.normal").slideDown();
        $("p.fast").slideDown("fast");
        $("p.slow").slideDown("slow");
        $("p.very-fast").slideDown(50);
        $("p.very-slow").slideDown(2000);
    });
});
</script>

You can also specify a callback function to execute after method completion slideUp()slideDown().

<script>
$(document).ready(function(){
    // Display alert message after sliding up paragraphs
    $(".up-btn").click(function(){
        $("p").slideUp("slow", function(){
            // Code to be executed
            alert("The slide-up effect is completed.");
        });
    });
    
    // Display alert message after sliding down paragraphs
    $(".down-btn").click(function(){
        $("p").slideDown("slow", function(){
            // Code to be executed
            alert("The slide-down effect is completed.");
        });
    });
});
</script>
Method slideToggle()

The jQuery method slideToggle() show or hide selected elements by animating their height so that if the element is initially displayed, it will be scrolled up; if hidden, it will be scrolled down, i.e. toggles between methods slideUp() e slideDown().

<script>
$(document).ready(function(){
    // Toggles paragraphs display with sliding
    $(".toggle-btn").click(function(){
        $("p").slideToggle();
    });
});
</script>

Similarly, you can specify the lifetime parameter for the method slideToggle() like slideUp()slideDown().

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.
<script>
$(document).ready(function(){
    // Slide Toggles paragraphs with different speeds
    $(".toggle-btn").click(function(){
        $("p.normal").slideToggle();
        $("p.fast").slideToggle("fast");
        $("p.slow").slideToggle("slow");
        $("p.very-fast").slideToggle(50);
        $("p.very-slow").slideToggle(2000);
    });
});
</script>

Similarly, you can also specify a callback function for the method slideToggle().

<script>
$(document).ready(function(){
    // Display alert message after slide toggling paragraphs
    $(".toggle-btn").click(function(){
        $("p").slideToggle(1000, function(){
            // Code to be executed
            alert("The slide-toggle effect is completed.");
        });
    });
});
</script>

Animation effects

Method animate()

The jQuery method animate() it is used to create custom animations. The method animate() is used to animate numeric CSS properties, such as width, height, margin, padding, opacity, top, left etc. but non-numerical properties like colorbackground-color they cannot be animated using basic jQuery functionality.

The basic syntax of the method animate() is the following:

$(selector).animate({ properties }, duration, callback);

Method parameters animate() have the following meanings:

  • The required properties parameter defifinish the CSS properties to animate.
  • The optional duration parameter specifies how long the animation will run. Durations can be specified using one of the pre stringsdefinight 'slow''fast', or in a number of milliseconds; higher values ​​indicate slower animations.
  • The optional callback parameter is a function to call after the animation is complete.

Below is a simple example of the method animate() which animates an image from its original position to the right by 300 pixels on button click.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("img").animate({
            left: 300
        });
    });
});
</script>

You can also animate multiple properties of an element together at once using the method animate(). All properties were animated at the same time without any delay.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".box").animate({
            width: "300px",
            height: "300px",
            marginLeft: "150px",
            borderWidth: "10px",
            opacity: 0.5
        });
    });
});
</script>

You can also animate multiple properties of an element one by one individually, in a queue using jQuery's concatenation function.

The following example shows a queued or chained jQuery animation, where each animation will start once the previous animation on the element has completed. We will see the concatenation function in a future article.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".box")
            .animate({width: "300px"})
            .animate({height: "300px"})
            .animate({marginLeft: "150px"})
            .animate({borderWidth: "10px"})
            .animate({opacity: 0.5});
    });
});
</script>

It is also possible definish relative values ​​for animated properties. If a value is specified with a prefix += o -=, the target value is calculated by adding or subtracting the specified number from the current value of the property.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".box").animate({            
            top: "+=50px",
            left: "+=50px",
            width: "+=50px",
            height: "+=50px"
        });
    });
});
</script>

In addition to numeric values, each property can accept strings 'show''hide''toggle'. It will be very useful in a situation where you just want to animate the property from its current value to its initial value and vice versa.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".box").animate({
            width: 'toggle'
        });
    });
});
</script>
Method stop()

The jQuery method stop() is used to stop currently running jQuery animations or effects on selected elements before completion.

The basic syntax of the method stop() jQuery can be given with:

$(selector).stop(stopAll, goToEnd);

The parameters in the above syntax have the following meanings:

  • Il optional parameter boolean stopAll, specifies whether or not to remove the queued animation. The predefinite is false, this means that only the current animation will be stopped, the rest of the animations in the queue will be executed later.
  • The boolean parameter goToEnd optional specifies whether to complete the current animation immediately. The predefinite is false.

Here is a simple example demonstrating the method stop() in real action where you can start and stop the animation on button click.

<script>
$(document).ready(function(){
    // Start animation
    $(".start-btn").click(function(){
      $("img").animate({left: "+=150px"}, 2000);
    });
 
    // Stop running animation
    $(".stop-btn").click(function(){
      $("img").stop();
    });
    
    // Start animation in the opposite direction
    $(".back-btn").click(function(){
      $("img").animate({left: "-=150px"}, 2000);
    });
 
    // Reset to default
    $(".reset-btn").click(function(){
      $("img").animate({left: "0"}, "fast");
    });
});
</script>

Here is another example of this method where if you click the button againSlide Toggle” after starting the animation but before it completes, the animation will immediately start in the opposite direction from the saved starting point.

<script>
$(document).ready(function(){
    // Kill and toggle the current sliding animation
    $(".toggle-btn").on("click", function(){
        $(".box").stop().slideToggle(1000);
    });
});
</script>

While creating the animated hover effect, one of the most common problems you may encounter is multiple animations queued up, when you quickly place and remove the mouse cursor. Why, in this situation, mouseenter The mouseleave events are fired quickly before the animation completes. To avoid this problem and create a nice and smooth hover effect, you can add stop(true, true)to the method chain, like so:

<script>
$(document).ready(function(){
    $(".box").hover(function(){
        $(this).find("img").stop(true, true).fadeOut();
    }, function(){
        $(this).find("img").stop(true, true).fadeIn();
    });
});
</script>

call Back

JavaScript statements are executed line by line. However, since the jQuery effect takes some time to finish, the next line's code might run while the previous effect is still running. To prevent this from happening, jQuery provides a callback function for each effect method.

A callback function is a function that runs once the effect is complete. The callback function is passed as an argument to the effect's methods, and they usually appear as the last method argument. For example, the basic syntax of the jQuery effect method slideToggle() with a callback function that can be specified as follows:

$(selector).slideToggle(duration, callback);

Consider the following example where we have placed the statements slideToggle()alert()one beside the other. If you try this code, the alert will appear immediately after clicking the toggle button without waiting for the slide toggle effect to complete.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").slideToggle("slow");
        alert("The slide toggle effect has completed.");
    });   
});
</script>

And here is the modified version of the previous example where we inserted the statement alert() inside a callback function for the method slideToggle(). If you try this code, the warning message will appear once the slide toggle effect is completed.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").slideToggle("slow", function(){
            // Code to be executed once effect is complete
            alert("The slide toggle effect has completed.");
        });
    });   
});
</script>

Likewise, you can defifinish callback functions for the other jQuery effect methods, such as show(), hide(), fadeIn()fadeOut()animate(), etc.

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, p").slideToggle("slow", function(){
            // Code to be executed once effect is complete
            alert("The slide toggle effect has completed.");
        });
    });   
});
</script>

If you try the sample code above, you will get the same warning message twice once per item <h1><p>, after clicking on the activate button.

BlogInnovazione.it

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.
Tags: jQuery

Latest Articles

Veeam features the most comprehensive support for ransomware, from protection to response and recovery

Coveware by Veeam will continue to provide cyber extortion incident response services. Coveware will offer forensics and remediation capabilities…

April 23 2024

Green and Digital Revolution: How Predictive Maintenance is Transforming the Oil & Gas Industry

Predictive maintenance is revolutionizing the oil & gas sector, with an innovative and proactive approach to plant management.…

April 22 2024

UK antitrust regulator raises BigTech alarm over GenAI

The UK CMA has issued a warning about Big Tech's behavior in the artificial intelligence market. There…

April 18 2024

Casa Green: energy revolution for a sustainable future in Italy

The "Green Houses" Decree, formulated by the European Union to enhance the energy efficiency of buildings, has concluded its legislative process with…

April 18 2024