Skip to content

Instantly share code, notes, and snippets.

@ArcCosine
Created October 31, 2012 23:12
Show Gist options
  • Save ArcCosine/3990550 to your computer and use it in GitHub Desktop.
Save ArcCosine/3990550 to your computer and use it in GitHub Desktop.
refactor simple slide show code.
/**
* 簡易スライドショー
*
* nextボタンを押したときに画像を切り替える簡単な
* スライドショーのサンプルプログラムです。
* */
(function(document){
// 写真を表示
function showPhoto(){
var photos = document.querySelectorAll('#photo img'), i = 0, iz = photos.length;
// indexを増やす
showPhoto.index = (showPhoto.index+1 >= iz) ? 0 : showPhoto.index+1;
// 全写真を一旦非表示
for( ;i<iz; i++ ){
photos[i].style.display = 'none';
}
// 表示する対象の要素を取得
var targetPhoto = photos[showPhoto.index];
// 写真表示
targetPhoto.style.display = 'inline';
// タイトルを表示
document.getElementById('title').innerHTML = '[' + Number(showPhoto.index + 1) + '] ' + targetPhoto.alt;
}
// DOM生成
function createPhotoList(){
//写真のリストの定義
var photoList = [
{ src: 'img/spring.jpg', title: '春の桜' },
{ src: 'img/summer.jpg', title: '夏のひまわり' },
{ src: 'img/autumn.jpg', title: '秋の紅葉' },
{ src: 'img/winter.jpg', title: '冬の山' }
],
photo = document.getElementById('photo'),
item, img;
// 作成したimg要素をHTMLに追加+img要素を作成
photoList.forEach(function(item){
img = photo.appendChild(document.createElement('img'));
img.src = item.src;
img.alt = item.title;
});
}
function init(){
// 写真一覧のDOM生成
createPhotoList();
// 初期表示のためにshowPhotoを一度だけ実行する
showPhoto.index = -1;
showPhoto();
//イベントの設定
document.getElementById('nextBtn').addEventListener("click", showPhoto, false );
}
// 読み込み時実行
document.addEventListener('DOMContentLoaded', init, false );
})(document);
@ArcCosine
Copy link
Author

http://webtech-walker.com/archive/2012/10/jsippo_release_intro.html
↑のコードをリファクタしました。

IEで動かないって? 知るか。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment