Toggle image in pure javascript

Morten Hjort

I now have a player icon that changes to the pause-icon when playing. I'm using this code for changing it:

    <script>
      var onImg= "img/play.svg";
      var offImg= "img/pause.svg";
    </script>

However it only goes one-way and don't revert back to the play icon when clicked yet again. How can I archive this? I can only find jQuery code, but I want to have a solution thats not dependent on any libraries.

Link to demo: http://mortenhjort.dk/synchub/v2/ (first cover works with audio)

Marco Dal Zovo

Take a look at this:

var on = "http://webneel.com/wallpaper/sites/default/files/images/04-2013/15-beach-sea-photography.preview.jpg";
var off = "https://s13.postimg.org/lzdaqr6fr/15_beach_sea_photography_preview_Convert_Image.jpg";
var state = false;
var img = document.getElementById("img");

img.onclick = function(){
	if(state){
  	img.src = off;
    state = false;
  }
  else{
  	img.src = on;
    state = true;
  }
}
<img src="http://webneel.com/wallpaper/sites/default/files/images/04-2013/15-beach-sea-photography.preview.jpg" id="img">

The solution is the same when you need to change the play icon with a pause icon... hope it helps :)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related