+ 1
HTML and JavaScript how to make a text with popup message that fades a way after two seconds?
I want to write a code in html and JavaScript so when I click a text it should say coming soon but the message fades away after two seconds. Preferably if the popup message displays under the text not above it.
2 Answers
+ 1
JaScript Thank you for the replay. But the popup does not go away after two seconds.
0
What you're looking for is something called a *modal* (or modal dialog). Certain libraries like jQuery, Bootstrap, and Bulma make this easier, but here's the general HTML:
<body>
Normal text here
<button onclick='showModal()'>Click for alert!</button>
<div id='my-modal' class='hide'>Hey! You clicked me!</div>
</body>
And the CSS:
.hide{
display:none;
}
And the JavaScript:
function showModal(){
const modal = document.querySelector('#my-modal');
modal.classList.remove('hide');
setTimeout(function(){
modal.classList.add('hide');
},2000);
}
Basically, the button triggers a function. In that function, we remove the "hide" class (that hides our modal). Finally, we have a setTimeout that runs after 2000 milliseconds and re-adds that "hide" class.
One important note here is that the modal is what we call *non-blocking*. In other words, if you have:
showModalFunction();
afterModalFunc();
then "afterModalFunc()" will not "wait" for the modal to disappear. There are ways to get around this (look up "callbacks") but those are another topic.