How to add a delay to this onclick function

Could be possible to delay two seconds when my image appears using setTimeout

var openImg = document.getElementById('openImg');
openImg.onclick = function() {
    myPic.style.display = "block";
}

Sure, just call setTimeout in the click handler:

openImg.onClick = function() {
  setTimeout( function () { myPic.style.display = "block"; }, 2000);
} 

I prefer:

document.getElementById('openImg').addEventListener('click', () => {
   setTimeout(() => {
	document.querySelector('img').classList.add('show_me')
   }, 1000);
});
img {
  width: 200px;
  display: none;
}

img.show_me {
  display: block;
}

https://jsfiddle.net/o7Lcesna/

Let CSS do the styling…

Avoid .onClick(),. use addEventListener()

1 Like