Skip to content

Instantly share code, notes, and snippets.

@danielrob
Created May 24, 2016 17:49
Show Gist options
  • Save danielrob/3f83d802963e04d02b808104569a023d to your computer and use it in GitHub Desktop.
Save danielrob/3f83d802963e04d02b808104569a023d to your computer and use it in GitHub Desktop.
img-load-play
<style>
/*#preload img {
width: 1px;
height: 1px;
opacity: 0.01;
}*/
</style>
<button>Toggle Image</button>
<div id="container"></div>
<div id="preload"></div>
<script>
"use strict"
const button = document.getElementsByTagName('button')[0]
, container = document.getElementById('container')
, preload = document.getElementById('preload')
, img1 = new Image()
, img2 = new Image()
var current = img2
img1.src = './img1.JPG'
img2.src = './img2.JPG'
preload.appendChild(img2)
setTimeout(function(){
preload.removeChild(preload.childNodes[0])
}, 200)
button.addEventListener('click', function(e){
toggleImg()
})
function toggleImg(){
if (current === img1) {
setImg(img2);
} else {
setImg(img1)
}
}
function setImg(img){
if (container.hasChildNodes()) container.removeChild(container.childNodes[0])
container.appendChild(img)
current = img
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment