Delete HTML Widget after a few seconds

Asked

Viewed 4,124 times

3

Next person, I have a registration script, which when registering a user successfully, performs the following command to appear a message on the screen:

echo "<p class='msg-success'> Usuário Cadastrado com sucesso!</p>";

My question is:
How can I make after a certain period, like 5 seconds, the message disappear?
How can I delete that paragraph echo created?

  • 2

    Javascript might be better to do this, since in php, you would need to update the page again.

  • I thought about it tbm, but I would need a way to capture the moment the message appears on the screen with Javascript, in order to destroy it at some point. I have no idea how to do it.

  • Perhaps delegating the display and removal of the message using javascript, through jquery. It would be interesting for you to add the javascript and/or jquery tag if you accept answers based on these technologies.

  • True, I added. I’m going to do a search on a way to replace echo.

  • Put what you have in javascript done.

  • There was no code yet, I was trying to PHP before I left pro JS. But I will do like the answers below.

Show 1 more comment

2 answers

6


To manipulate any information in the browser (without making a new request to the server) you must use Javascript.

An example to remove the message after 5 seconds would be:

USING CLASS class='msg-success':

<!DOCTYPE html>
<html>
    <body>
        <p class='msg-success'> Usuário Cadastrado com sucesso!</p>
        <script>
            setTimeout(function(){ 
                var msg = document.getElementsByClassName("msg-success");
                while(msg.length > 0){
                    msg[0].parentNode.removeChild(msg[0]);
                }
            }, 5000);
        </script>
    </body>
</html>

USING ID id='msg-success':

<!DOCTYPE html>
<html>
    <body>
        <p id='msg-success'> Usuário Cadastrado com sucesso!</p>
        <script>
            setTimeout(function(){ 
                var msg = document.getElementById("msg-success");
                msg.parentNode.removeChild(msg);   
            }, 5000);
        </script>
    </body>
</html>

Only current browsers are used:

Can substitute: msg.parentNode.removeChild(msg);

simply: msg.remove();

Example with jQuery with ID: id='msg-success':

<!DOCTYPE html>
<html>
    <body>
        <p id='msg-success'> Usuário Cadastrado com sucesso!</p>
        <script>
            setTimeout(function(){ 
                $('#msg-success').remove();   
            }, 5000);
        </script>
    </body>
</html>

Example with jQuery with CLASS: class='msg-success':

<!DOCTYPE html>
<html>
    <body>
        <p class='msg-success'> Usuário Cadastrado com sucesso!</p>
        <script>
            setTimeout(function(){ 
                $('.msg-success').remove();   
            }, 5000);
        </script>
    </body>
</html>

Time setting in setTimeout function:

Set in milliseconds, so: 5000 / 1000 = 5 segundos.

Combining with PHP:

My suggestion: create a Javascript function to remove the message and call this function each time the message appears.

If it is generated with PHP, it is generated along with page loading. Then with javascript, an alternative is to create a function to remove the message after 5 seconds, then monitor when the page is loaded and right after the page load call the function.

As a result, after 5 seconds the message is displayed it will be removed.

Javascript file:

function removeMensagem(){
    setTimeout(function(){ 
        var msg = document.getElementById("msg-success");
        msg.parentNode.removeChild(msg);   
    }, 5000);
}
document.onreadystatechange = () => {
    if (document.readyState === 'complete') {
      // toda vez que a página carregar, vai limpar a mensagem (se houver) 
      // após 5 segundos
        removeMensagem(); 
    }
};

PHP file:

echo "<p id='msg-success'> Usuário Cadastrado com sucesso!</p>";

2

An example using JavaScript.

Basically the script does:
1. Starts execution of processes after full page loading.
2. Sets "empty" visibility after 5 seconds.

Important to pay attention when using Document.getElementsByClassName().
As commented in the code below, an array or a list of nodes is returned (Node list).
Read the comments within the example code.

/*
 * Colocamos dentro de um evento window.onload para que comece a execução
 * somente após a página inteira carregar.
 */
window.onload = function() {
    setTimeout(function(){
        // nome da classe do objeto que deseja manipular
        var e = "msg-success"; 

        // obtém o objeto pelo nome da classe
        var o = document.getElementsByClassName(e);                 

       /* 
        * Define a visibilidade como "none". 
        * Dá o mesmo efeito visual de como se estivesse removido.
        * Note que getElementsByClassName retornará uma lista de nós(NodeList).
        * Portanto, para acessar o elemento desejado, é necessário especificar 
        * qual a chave onde ele se encontra. 
        * No exemplo é obviamente a chave 0 (zero) pois é único.
        */
 
        o[0].style.display = 'none';
        
    }, 5000); // O tempo em milisegundos. 1 segundo = 1000 milisegundos.
};
<p class='msg-success'> Usuário Cadastrado com sucesso!</p>

Note

Instead of setting the visibility, I could present an example of how to remove the object. However, I preferred to show a simpler way that solves in the same way with less cost. The reason is that to remove more securely, you need a slightly more complex script than just invoking element.parentNode.removeChild(element);

Something safer would be to create a method in the prototype:

Element.prototype.remove = function() {
    this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
    for(var i = this.length - 1; i >= 0; i--) {
        if(this[i] && this[i].parentElement) {
            this[i].parentElement.removeChild(this[i]);
        }
    }
}

Then you could do just like this:

element.remove();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.