Skip to content Skip to sidebar Skip to footer

How To Build A Simple Image Gallery In Javascript Using Popup Window

I have looked all over the internet for help but I can't get it to work! Would someone be able to give me an example of how to code something like this? I would resize an image, an

Solution 1:

Image gallery in 9 lines of JavaScript.

All you have to do - create two directories, one for images and one for thumbnails; the thumbnails directory should be placed within the images directory. Image name should be the same. Use the alt attribute for an image description and finally, feel free to change CSS values.

// HTML
<ul id="gallery">
    <li><img src="images/thumbnails/img-01.jpg" alt="desc-01"></li>
    <li><img src="images/thumbnails/img-02.jpg" alt="desc-02"></li>
    <li><img src="images/thumbnails/img-03.jpg" alt="desc-03"></li>
    <li><img src="images/thumbnails/img-04.jpg" alt="desc-04"></li>
</ul>

// CSS#gallery {list-style-type:none; background-color: #f0f0f0; overflow: hidden; margin: 0px; padding: 0px;
}

#gallery li {
    background-color: #fff; float: left; margin: 5px; padding: 5px;
}

#gallery li img {
    width: 120px; height: 120px; margin: 0px; padding: 0px;
}

//// Image gallery in 9 lines of JavaScript// http://stackoverflow.com/users/1310701/hex494d49//
window.onload = function() {
    var img = document.getElementById("gallery").getElementsByTagName("IMG"), w, i;
    for (i = 0; i < img.length; i++){
        (function(i){
            img[i].onclick = function() {
                w = window.open("","gallery","menubar=0,scrollbars=0");
                w.document.write("<img src='" + img[i].src.replace(/thumbnails\//,'') + "' alt='" + img[i].alt + "' /><div>" + img[i].alt + "</div>");
            };
        }(i));
    }
};

Image gallery in 15 lines of JavaScript.

// HTML// The same as above// CSS// The same as above// // Image gallry in 15 lines of Javascript// http://stackoverflow.com/users/1310701/hex494d49//window.onload = function() {
    var img = document.getElementById("gallery").getElementsByTagName("IMG"), w, i;
    for (i = 0; i < img.length; i++) {
        (function(i) {
            img[i].onclick = function() {
                if (!w || w.closed) {
                    w = window.open("","gallery","menubar=0,scrollbars=0");
                    w.document.write("<img src='" + img[i].src.replace(/thumbnails\//,'') + "' alt='' /><div>" + img[i].alt + "</div>");
                } else {
                    w.document.getElementsByTagName('IMG')[0].src = img[i].src.replace(/thumbnails\//,'');      
                    w.document.getElementsByTagName('DIV')[0].innerHTML = img[i].alt;
                }
                w.focus();
            };
        }(i));
    }
};

Check the first or the second working version.

Post a Comment for "How To Build A Simple Image Gallery In Javascript Using Popup Window"