Search code examples
javascripteventsonclickinline

Toggling image onclick event inline


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 class="first-image" src="/first-image.png" onclick="this.src=\'/second-image.png\'" alt="my images">


Solution

  • 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">