Fade In and Fade Out Messages with jQuery

jQuery provides a simple method to apply fade in and fade out effects for your HTML elements. Below is an example of how we can achieve the fade in and fade out effect for a message.
 
The HTML

Here we have a simple button that will open the message, the message box itself, and embedded within message box, a button to close the message box.

<button id="showBtn">Click Me!</button>
<div id="messageBox" class="demoMessage"> 
   Action  Successful! <button id="hideBtn">Close</button>
</div>

 
The CSS

In the CSS, we simply have a class to add some style to the message box. Note that we initial hide the message using “display: none;”.

.demoMessage
{
   display: none;
   background-color:green;
   color: #fff;
   padding: 5px;
   width:200px;
}

 
The JavaScript

Here is the jQuery that will open and close the message box:

  • Lines 2-4 will apply the fadeIn() function to the “messageBox” div when the “showBtn” button is clicked. This will fade in the div.
  • Lines 5-7 will apply the fadeOut() function to the “messageBox” div when the “hideBtn” button is clicked. This will fade out the div.
$(document).ready(function(){
    $("#showBtn").click(function(){
        $("#messageBox").fadeIn();
    });
    $("#hideBtn").click(function(){
        $("#messageBox").fadeOut();
    });
});

 
The Live Demo

Action Successful!


 

Share on FacebookTweet about this on TwitterShare on LinkedInShare on Google+Pin on PinterestShare on RedditShare on StumbleUponShare on TumblrDigg this

You may also like...

1 Response

  1. sanam bolach says:

    thank you for this post ….

Leave a Reply

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