Konstantinos-infogeek
3/28/2015 - 4:59 PM

Example javascript gallery

Example javascript gallery

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <meta lang="en">

        <title>Upload Example</title>

        <link rel="stylesheet" media="all" href="style.css" />
    </head>
    <body>

        <div class="wrapper">

        </div>
        <div style="margin-top: 20px;">
            <input type="file" accept="image/*" id="upload">
        </div>

        <script type="text/javascript" src="script.js"></script>

    </body>
</html>

#A Basic Gallery, with javascript

It doesn't save images, just load and display them with javascript.

var imagesSrc = [];
var boxes = [];
var uploader = document.getElementById('upload');

//Setup event listener
uploader.addEventListener('change', loadImage);

function loadImage(evt) {
    var uploadElem = evt.target;

    if (uploadElem.files && uploadElem.files[0]) {
        var reader = new FileReader();
        reader.readAsDataURL(uploadElem.files[0]);

        reader.onload = function (evt) {
            imagesSrc.push(evt.target.result);
            createBox();
            parseImages(imagesSrc);
        }
    }
}

function parseImages(images) {
    var counter = 0;

    for (; counter < images.length; counter = counter + 1) {
        boxes[counter].setAttribute('style', 'background-image: url(' + images[counter] + ')');
    }
    document.getElementsByClassName('wrapper')[0].innerHTML = boxes.map(function (a) {
        return a.outerHTML;
    }).join('');
}

function createBox() {
    var box = document.createElement('div');
    box.setAttribute('class', 'box');
    boxes.push(box);
}
.wrapper {
    display: block;
    width: 100%;
    min-height: 500px;
}
.wrapper:after {
    display: block;
    content: " ";
    clear: both;
}

.box {
    width: 500px;
    height: 300px;
    background-color: lightgrey;
    background-size: 100%;
    background-repeat: no-repeat;
    float: left;
    margin-right: 1em;
    margin-bottom: 1em;
}