JQuery Fade Effects

In the last tutorial we studied how to hide and show elements using JQuery. This article extends the last article and explains JQuery fade effects. There are four types of fade effects in JQuery: fadeIn(), fadeOut(), fadeToggle() and fadeTo. This article touches the first two of them. The fadeToggle and fadeTo are just extensions of the first two.

Fading in Elements via fadeIn()

The fadeIn() function takes two optional parameters: speed and callback. Speed parameter defines the speed with which the element fades into the page. it can take values like “slow”, “fast” or milliseconds. The callback is the function which executes when the fadeIn() function completes its functionalities. We shall see call backs in the later sections. Take a look at this example.

<!DOCTYPE html>
<html>
<head>
    
    <title>FadeIn Effect</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    
    <script type = "text/javascript">
         $(document).ready(function() {
         $("button").click(function(){
           $('h1').fadeIn(1000);
            $('p').fadeIn('fast');
            
         });
           
         });
      </script>
    <style>
        h1,p{display: none;}
    </style>
</head>
    
<body>
    
    <button>Click to see fadein in action.</button>
    <h1> This is a heading</h1>
    <p>This is a random paragraph</p>
    
    
</body>

</html>

Download Code
Run Code

The above html document contains a button, an h1 heading and a paragraph. When a user clicks button an event is fired which is handled by the click function. Inside this function, h1 and p elements are selected. The speed for fading in h1 is 1 seconds, while for paragraphs, it is fast. Notice that both h1 and paragraph are hidden by default. Once, the page loads you will only see a button. Clicking this button will fade in both h1 and paragraph.

Fading out Elements via fadeOut()

FadeOut function is similar to fadeIn() function, it also takes two parameters: speed and callback. Take a look at the following example to understand this.

<!DOCTYPE html>
<html>
<head>
    
    <title>FadeOut Effect</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    
    <script type = "text/javascript">
         $(document).ready(function() {
         $("button").click(function(){
           $('h1').fadeOut(1000);
            $('p').fadeOut('fast');
            
         });
           
         });
      </script>
</head>
    
<body>
    
    <button>Click to see fadeout in action.</button>
    <h1> This is a heading</h1>
    <p>This is a random paragraph</p>
    
    
</body>

</html>

Download Code
Run Code

In the above code, clicking the button will fade out both h1 and paragraph elements from the webpage.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .