Delete HTML Element after a few seconds

3

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

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

My question is:
How can I do for after a certain period, like 5 seconds, the message disappears? How can I delete this paragraph that echo created?

    
asked by anonymous 21.08.2016 / 01:38

2 answers

6

To manipulate any information in the browser (without making a new request to the server) you should 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>

If you only use current browsers:

You can substibuir: msg.parentNode.removeChild(msg);

by 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>

Setting the time in the setTimeout function:

Defined in milliseconds, hence: 5000 / 1000 = 5 segundos.

Combining with PHP:

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

If it is generated with PHP, it is generated along with page loading. So with javascript, an alternative is to create a function to remove the message after 5 seconds, then monitor when the page loads and soon after loading the page 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>";
    
21.08.2016 / 04:21
2

An example using JavaScript .

Basically the script does:
1. Starts running 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 node list is returned. Read the comments inside the sample 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 form that solves the same way with less cost. The reason is that to remove more securely, you need a script a little more complex than just invoking element.parentNode.removeChild(element);

Something safer would be to create a method in 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]);
        }
    }
}

So I could do just that:

element.remove();
    
21.08.2016 / 05:22