Computers & ProgrammingFrontend DevelopmentjQuery

jQuery Fading Effects

jQuery has several methods that can be used to adjust the opacity of elements. These methods are just a few of the variety of methods that can be used to create animation effects.

The use of jQuery among web designers continues to be growing in popularity. With regard to fading techniques, the typical methods used are fadeIn(), fadeOut(), fadeTo(), and fadeToggle().

Syntax

$(selector).fadeIn(speed,callback)
$(selector).fadeOut(speed,callback)
$(selector).fadeTo(speed,opacity,callback)
$(selector).fadeToggle(speed,easing,callback)
ParameterDescription
speedOptional values in milliseconds, “slow”, “normal”, and “fast”.
opacityRequired attribute that specifies the opacity to fade to, between 0.00 and 1.00.
easingIndicates which easing function (swing/linear) to use for the transition.
callbackAn optional function to run after the method is completed.

HTML Example

We will use the following HTML for the examples listed below.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            // ... jQuery Code ...
        });
    </script>
</head>
<body>
    <img id="img1" src="fadeIn.png" />  
    <img id="img2" src="fadeOut.png" /> 
    <div id="div1"> <!-- Some Content --> </div>
</body>
</html>

FadeIn / FadeOut

In the following example, we will use the click event to trigger the fadeIn() and fadeOut() method on the div element adjacent to the images.

<script type="text/javascript">
    $("#img1").click(function(){
        $("div").fadeOut(); 
    });
    $("#img2").click(function(){
        $("div").fadeIn(); 
    });
</script> 

FadeTo

In the following example, we will use the click event to trigger the fadeTo() method to apply this fading effect to the adjacent div element.

<script type="text/javascript">
    $("#img1").click(function(){
        $("div").fadeTo("normal", 0.20); 
    });
</script> 

FadeToggle

The fadeToggle() method animates the opacity of the matched elements. When triggered on an element, the element’s display style property is set to none once the opacity reaches 0.

<script type="text/javascript">
    $("#img1").click(function(){
        $("div").fadeToggle("slow", "linear"); 
    });
</script> 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top