Utilizing vanilla JavaScript, begin by setting the default opacity of the #example
element to 0. When the #alert-trigger
button is clicked, change the opacity to 1 and then use the setTimeout() method to revert it back to 0 after a second.
For jQuery, start by hiding the #example
element by default. Simply apply the fadeIn() method to fade it in upon click, followed by utilizing both the setTimeout() method and the fadeOut() method to fade out the element after a specified time interval.
Below are practical examples of my explanations through the following Code Snippets:
Implementing Pure JavaScript Method:
/* JavaScript */
const btn = document.getElementById("alert-trigger");
const box = document.getElementById("example");
btn.addEventListener("click", function(){
box.style.opacity = 1;
setTimeout(function(){box.style.opacity = 0}, 1000);
});
/* CSS */
body {text-align: center;}#alert-trigger{background-color: green; padding: 5px; color: #FFF;}
#example {background-color: grey;padding: 10px;margin: 10px 0px;
opacity:0; /* initial opacity value set to 0 */
transition: all 1s; /* will fade the element instead of hiding/showing the element instantly */
}
<!-- HTML -->
<button id="alert-trigger">Trigger Alert</button>
<div id="example" >
<h2>Box Content Here:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus quia dolore cumque aliquid eaque nisi, eos praesentium delectus tempore quidem? Iure tenetur cupiditate, laborum, saepe aut alias voluptatem impedit molestias.</p>
</div>
Using jQuery Technique:
/* JavaScript */
$("#alert-trigger").on("click", function(){
$("#example").fadeIn(); // fade in the example div
setTimeout(function(){
$("#example").fadeOut(); // fade out the example div
}, 1000);
})
/* CSS */
#example {display:none;} /* initially hide it by default */
<!-- HTML -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="alert-trigger">Trigger Alert</button>
<div id="example" >
<h2>Box Content Here:</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus quia dolore cumque aliquid eaque nisi, eos praesentium delectus tempore quidem? Iure tenetur cupiditate, laborum, saepe aut alias voluptatem impedit molestias.</p>
</div>