How to create an element and after a few defined seconds remove it?

Asked

Viewed 3,358 times

6

I need to create a label warning like this:

 <p id="lblAviso">Salvo com sucesso</p>

And remove it after 3 seconds.

How to do this with ? Needs some plugin?

4 answers

14


You can use it like this:

var aviso = '<p id="lblAviso">Salvo com sucesso</p>';
var destino = $('#destinoAviso');

//codigo que você quer:
destino.append(aviso);
setTimeout(function(){
    $('#lblAviso').remove();
},3000);

Example


Another example using fade in/out, hiding the element directly in CSS.

In this example use:

  • setTimeout() which is used to execute code within the anonymous function once, and where the last parameter is time counter (in milliseconds) to execute the code.
  • .append(), one of jQuery’s methods for inserting content into a given DOM element.

You can also use a jQuery string, using the .delay() and calling the callback function of the .fadeOut() to remove the element when the animation comes to an end.

So, and making note to CSS #lblAviso { display:none; }, the code can be:

$('#lblAviso').fadeIn().delay(3000).fadeOut(function () {
    $(this).remove()
});

Example


Another example, using an overlay (overcoat).

  • 1

    Very good! Thank you!

  • As an alternative to adding and removing the element every time, I suggest having the fixed element on the page and just hide it or show it using .show and .hide (or .toggle(true|false)).

  • @mgibsonbr, you’re right, I added more alternatives.

  • @Joaopaulo, I added more alternatives. Aultima with an overlay. You can also use . show() / . Hide() at fade in/out.

4

You can instead remove it immediately from the page, hide it in an animated way by controlling the animation time:

$lblAviso = $('<p id="lblAviso">Salvo com sucesso</p>'); // cria o elemento
$lblAviso.hide(); // atribui o elemento como escondido (apesar de ainda não estar na página)
$('#conteudo').append($lblAviso); // adiciona o elemento a outro elemento
$lblAviso.fadeIn(); // exibe o elemento com animação de fade (animação rápida)
$lblAviso.fadeOut(3000); // esconde o elmento com animação de fade (a animação dura 3 segundos)

Example

If you find it necessary to remove the page element change the last line of the example to:

$lblAviso.fadeOut(3000, function() {  $lblAviso.remove(); });

4

An interesting way is to display the warning and remove with a fade out:

$('<p id="lblAviso">Salvo com sucesso</p>')
  .appendTo('body')
  .delay(1000)
  .fadeTo("slow", 0, function() { $(this).remove(); });

Note that at the end, the element is removed.

See the functional example in jsfiddle.

2

There are already numerous very good answers to deal with the question asked, I will just leave a different and abstract example of the target element, which can serve for future visitors.

Introducing

Create a "mini" jQuery extension that allows you to add warning, success, information or error captions to any element on the page, allowing you to reuse the same code snippet in multiple situations.

See example in Jsfiddle, with some CSS formatting for demo!

jQuery

;(function ($) {

    $.fn.goLabel = function( options ) {

        var opts = $.extend({
            type: "success",
            message: "guardado com sucesso",
            time: 3000
        }, options );

        var $label = $('<span/>', {"class": "label"}).addClass(opts.type).html(opts.message);

        return this.append($label).find('.label').delay(opts.time).fadeOut(300, function(){
            $(this).remove();
        });
    };
}( jQuery ));

Utilizing:

The use is simple, through a id or class, we call the goLabel() with the desired options:

// assumindo as opções por defeito
$( "#devicePrice" ).goLabel();

// com personalização das opções
$( "#newsletterStatus" ).goLabel({
    type: "info",
    message: "receber é muito bom",
    time: 3000
});

Browser other questions tagged

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