Home > front end >  how to change image onclick for few seconds using javascript
how to change image onclick for few seconds using javascript

Time:06-27

i have a an image section where onclick i want to change it for few seconds and make it back to original image after few seconds, i did the following code:

<img src="contacticons.jpg" usemap="#image-map" id="imgName">
<a onclick="document.getElementById('imgName').src='../newImgSrc.jpg';"></a>

can anyone please tell me how to change it for few seconds and take it back to original image, thanks in advance

CodePudding user response:

Use setTimeout() Function.

<script>
const myTimeout = setTimeout(imgChange, 1000);
document.getElementById("img").src= "https://newimageurl.com"
function imgChange() {
  document.getElementById("img").src= "https://orignalurl.com"
}
</script>

CodePudding user response:

function ChangeImage()
{
  var originalImage = $("#imgName").attr("src");
  var changeImage = $("#imgName").data("changeimage");
  $("#imgName").attr("src",changeImage);  
  setTimeout(function(){
  $("#imgName").attr("src",originalImage);
  }, 1000);

  
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://images.unsplash.com/photo-1498598457418-36ef20772bb9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" usemap="#image-map"  id="imgName" height="50"
data-changeimage="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg">

<a onclick="ChangeImage()">change</a>

CodePudding user response:

No need using id, just call a function using the onclick event.

function changeImg(objImg, newSrc) {
  const originalSrc = objImg.getAttribute('src');
  objImg.setAttribute('src', newSrc);

  setTimeout(() => {
    objImg.setAttribute('src', originalSrc);
  },1000);
}   
<img onclick="changeImg(this, 'https://nodejs.org/static/images/logo.svg');"
  src="https://nodejs.org/static/images/openjs_foundation-logo.svg" />

  • Related