views:

3923

answers:

3

Is it possible to automatically hide an element in a web page 5 seconds after the form loads using jQuery?

Basically, I've got

<div id="successMessage">Project saved successfully!</div>

that I'd like to disappear after 5 seconds. I've looked at jQuery UI and the hide effect but I'm having a little trouble getting it work the way I want it to.

<script type="text/javascript">
        $(function() {
            function runEffect() {

                var selectedEffect = 'blind';

                var options = {};

                $("#successMessage").hide(selectedEffect, options, 500);
            };

         $("#successMessage").click(function() {
          runEffect();
          return false;
         });
        });
    </script>

I'd like the click function to be removed and add a timeout method that calls the runEffect() after 5 seconds.

mucho gracias!

+6  A: 
$(function() {
    // setTimeout() function will be fired after page is loaded
    // it will wait for 5 sec. and then will fire
    // $("#successMessage").hide() function
    setTimeout(function() {
        $("#successMessage").hide('blind', {}, 500)
    }, 5000);
});

Note: In order to make you jQuery function work inside setTimeout you should wrap it inside

function() { ... }
Koistya Navin
A: 

You use setTimeout on you runEffect function :

function runEffect() {
    setTimeout(function(){
        var selectedEffect = 'blind';
        var options = {};
        $("#successMessage").hide(selectedEffect, options, 500)
     }, 5000);
}
CMS