-2

I'm trying to make an image disappear after like 2 seconds but I don't know how to do it.

I've looked online but haven't really found anything useful.

function rockImage() {
    var img = document.createElement("img");
    img.src = "rock.png";
    var src = document.getElementById("compChoiceImage");
    img.setAttribute("width", "100");
    src.appendChild(img);
}

That's the function to create the image I want to add the timer thing into the function.

Oliver
  • 1

2 Answers2

0

Use setTimeout() with removeChild():

function rockImage() {
    const img = document.createElement('img');
    img.src = 'https://via.placeholder.com/100';
    img.setAttribute('width', '100');
    
    const parent = document.getElementById('div');
    parent.appendChild(img);
    
    setTimeout(() => parent.removeChild(img), 3000);
}

rockImage();
<div id="div"></div>
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

You could set display style to none in the setTimeout function:

function rockImage() {
  var img = document.createElement("img");
  img.src = "https://nyppagesix.files.wordpress.com/2018/04/gettyimages-901333660.jpg?quality=90&strip=all&w=618&h=410&crop=1";
  var src = document.getElementById("compChoiceImage");
  img.setAttribute("width", "100");
  src.appendChild(img);
  setTimeout(() => {
    img.style.display = "none";
  }, 2000);
}

rockImage();
<div id="compChoiceImage"></div>
shrys
  • 5,860
  • 2
  • 21
  • 36