Home > Enterprise >  Toggling image onclick event inline
Toggling image onclick event inline

Time:10-31

Managed with the snippet below to change from the first image to the second image using the inline onclick javascript event. My question is; is there a way to change the second image back to first image when clicking on the second image with another inline Javascript event? ie. without writing a function.

<img src="/first-image.png" onclick="this.src=\'/second-image.png\'" alt="my images">

CodePudding user response:

You can update your code like this:

<img class="first-image" src="/first-image.png" onclick="this.src==='/first-image.png' ? this.src='/second-image.png' : this.src='/first-image.png'" alt="my images">

Here is a working example:

<img class="first-image" src="https://photo-works.net/images/europe-landscape-photo-edited.jpg" onclick="this.src==='https://photo-works.net/images/europe-landscape-photo-edited.jpg' ? this.src='https://thumbs.dreamstime.com/b/landscape-nature-mountan-alps-rainbow-76824355.jpg' : this.src='https://photo-works.net/images/europe-landscape-photo-edited.jpg'" alt="my images">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could store both urls as properties of image tag, like this:

<img
  src="/first-image.png"
  data-src-1="/first-image.png"
  data-src-2="/second-image.png"
  onclick="this.src = this.src === this.getAttribute('data-src-1') ? this.getAttribute('data-src-2') : this.getAttribute('data-src-1')"
/>
  • Related