How to Hide DIV Element After Some Time Interval using jQuery

Hide HTML elements automatically can be used for many purposes. The status message section is the most effective area to apply the auto-hide feature in HTML. Whenever a form is submitted or completed a task, the status message is displayed on the web page. It will be a great idea to hide the message DIV after some seconds automatically from the element.

In this tutorial, we will show you how to hide DIV element after some time interval using jQuery. Not only DIV element, you can autohide any HTML element after few seconds in jQuery.

The following code snippet shows how to hide a message after 5 seconds using jQuery.

HTML Element:
The alert DIV element holds the status message in HTML.

<div class="alert">
    The requested operation is completed successfully!
</div>

jQuery Library:
First, include the jQuery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

JavaScript Code:
Use the fadeTo() method with slideUp() to hide the message block (.alert) after 5 seconds from HTML elements using jQuery.

<script>
$(document).ready(function() {
    $(".alert").fadeTo(5000, 500).slideUp(500, function(){
        $(".alert").slideUp(500);
    });
});
</script>

You can set the auto-hide time in duration parameter of fadeTo() method as required.

.fadeTo(duration, opacity)

Leave a reply

keyboard_double_arrow_up