pr -
pr -

Reputation: 358

How do I remove a div a second after it appears?

I'm trying to make a background effect. On keypress it creates a div with that fades out after half a second. Every time a key is pressed, it creates a new div with a new id. How do I remove each div half a second after it was triggered?

I forgot to mention, I have a function that shortens document.getElementById('id') to $('id'). I'm not using jQuery.

Here's my code so far.

function $(e) {
  return document.getElementById(e)
}

let circles = 0;
onkeypress = () => {
  document.body.insertAdjacentHTML('beforeend', `<div class="effect" id="l${circles}"></div>`)
  setTimeout(function(){
    $(`l${circles}`).remove()
  },500)
  circles++
}

Upvotes: 2

Views: 149

Answers (2)

Dan Dao
Dan Dao

Reputation: 21

onkeypress = () => {
    document.body.insertAdjacentHTML('beforeend', `<div class="effect" id="l${circles}"></div>`)
    setTimeout(function() {
        $(`l${circles}`).remove()
        circles++
    }, 500)
}

Upvotes: 2

mck89
mck89

Reputation: 19241

If you use setTimeout it will use the value of counter after 500ms, that means it's no longer equal to the counter applied to create the element's id.

You should just use:

onkeypress = () => {
    var el = document.createElement("div");
    el.className = "effect";
    document.body.appendChild(el);
    setTimeout(function(){
        document.body.removeChild(el);
    },500)
}

Upvotes: 3

Related Questions