Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
(function(){
var swaps = {
swap1: {
images : [
'james0.jpg',
'james1.jpg',
'james2.jpg'
]
},
swap2: {
images : [
'martha0.jpg',
'martha1.jpg',
'martha2.jpg'
]
}
}, p, t;
function swapImg(cfg){
t.src = 'images/' + cfg.images[cfg.x = ++cfg.x % cfg.images.length];
}
swapImg.preload = function(images){
var i = 0;
while(images[++i]){
(function(im){
var nim = new Image();
nim.src = 'images/' + im;
})(images[i]);
}
};
for(p in swaps){
swaps[p].x = 0;
swapImg.preload(swaps[p].images);
}
function swaponclick(e){
e = e || event;
t = e.target || e.srcElement;
swaps[t.id] && swapImg(swaps[t.id]);
}
document.addEventListener && document.addEventListener('click', swaponclick, false) ||
!document.addEventListener && document.attachEvent && document.attachEvent('onclick', swaponclick);
})();
</script>
</head>
<body>
<img id="swap1" src="images/james0.jpg" width="100" height="100" alt="james image" title="James Image"><br>
<img id="swap2" src="images/martha0.jpg" width="100" height="100" alt="martha image" title="Martha Image"><br>
</body>
</html>
Or the more compact, yet more verbose (changes highlighted):
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
(function(){
var swaps = {}, p, t;
swaps.swap1 = {images: []};
swaps.swap1.images[0] = 'james0.jpg';
swaps.swap1.images[1] = 'james1.jpg';
swaps.swap1.images[2] = 'james2.jpg';
swaps.swap2 = {images: []};
swaps.swap2.images[0] = 'martha0.jpg';
swaps.swap2.images[1] = 'martha1.jpg';
swaps.swap2.images[2] = 'martha2.jpg';
function swapImg(cfg){
t.src = 'images/' + cfg.images[cfg.x = ++cfg.x % cfg.images.length];
}
swapImg.preload = function(images){
var i = 0;
while(images[++i]){
(function(im){
var nim = new Image();
nim.src = 'images/' + im;
})(images[i]);
}
};
for(p in swaps){
swaps[p].x = 0;
swapImg.preload(swaps[p].images);
}
function swaponclick(e){
e = e || event;
t = e.target || e.srcElement;
swaps[t.id] && swapImg(swaps[t.id]);
}
document.addEventListener && document.addEventListener('click', swaponclick, false) ||
!document.addEventListener && document.attachEvent && document.attachEvent('onclick', swaponclick);
})();
</script>
</head>
<body>
<img id="swap1" src="images/james0.jpg" width="100" height="100" alt="james image" title="James Image"><br>
<img id="swap2" src="images/martha0.jpg" width="100" height="100" alt="martha image" title="Martha Image"><br>
</body>
</html>
Bookmarks