Could someone tell me how to make disappear a message after a few seconds?
$msg = '<h4 class="col-12 text-center mb-3 text-success">Sikeres rögzítés!</h4>';
After receiving the POST, it stays there and I need to reload to make it disappear.
Could someone tell me how to make disappear a message after a few seconds?
$msg = '<h4 class="col-12 text-center mb-3 text-success">Sikeres rögzítés!</h4>';
After receiving the POST, it stays there and I need to reload to make it disappear.
This has to be done client-side (i.e. in javascript) since PHP has finished after echoing the response (and, PHP only works server-side).
Here's a suggested algorithm (pseudo-code):
On the PHP side, add the class autovanish
(or whatever you want) to the element you want to automatically vanish after so many seconds.
$msg = '<h4 class="autovanish col-12 text-center mb-3 text-success">Sikeres rögzítés!</h4>';
Then, have a javascript function running all the time:
function autovanish(){
const avDivs = document.getElementsByClassName('autovanish');
if (avDivs.length){
setTimeout(() => {
avDivs[0].remove();
}, 3000); //removes the element after 3000ms
}
setTimeout(() => {autovanish();}, 500); //re-run every 500ms
}
In case you are not a js guy, you need the [0]
after avDivs
because getElementsByClassName
returns a collection, not a string.
If you need more assistance than this pseudo-code, ask in the comments.
Further to the code you posted, the top three lines are the part you were missing:
<script>
document.addEventListener('DOMContentLoaded',() => {
autovanish();
}
function autovanish(){
const avDivs = document.getElementsByClassName('autovanish');
if (avDivs.length){
setTimeout(function(){
avDivs[0].remove();
}, 3000); //removes the element after 3000ms
}
setTimeout(() => {autovanish();}, 500); //re-run every 500ms
}
</script>
Thank you for posting the full code - made it easy to see what's what. Two quick changes: (a) first, we need to start (i.e. "call") the autovanish function - otherwise it is just sitting there, but never runs. But before we do that: (b) We add an event listener for the DOMContentLoaded event and put the call to the autovanish function in there. The reason for that is because until all the elements on the page have been created, you might be trying to attach to an element that doesn't yet exist on the page. (In this example (b) is not important but it is a good concept for you to know for the future.) - cssyphus