JSFiddle - React, Tailwind, and code Playground
by hmdadou
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Image Gallery</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#preview {
max-width: 100%;
height: auto;
margin-bottom: 20px;
}
.gallery {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
margin-top: 20px;
}
.gallery img {
max-width: 100%;
height: auto;
margin: 5px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Image Gallery</h1>
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<label for="imageUpload">Select an image:</label>
<input type="file" id="imageUpload" name="imageUpload">
<input type="submit" id="submit" value="Add to gallery">
</form>
<div id="preview"></div>
<div class="gallery"></div>
</body>
</html>
JavaScript
// Check if local storage is supported
if (typeof(Storage) === "undefined") {
alert("Sorry, your browser does not support web storage...");
}
// Load the gallery
if (localStorage.getItem("pp-gallery")) {
var gallery = JSON.parse(localStorage.getItem("pp-gallery"));
gallery.reverse(); // Reverse the order of the gallery array to show most recent first
for (var i = 0; i < gallery.length; i++) {
// Check if image URL exists before displaying
$.get(gallery[i]).done(function() {
$(".gallery").append("<img src='" + gallery[i] + "' alt='Image " + (i+1) + "'/>");
}).fail(function() {
console.log("Image URL does not exist: " + gallery[i]);
});
}
}
// Preview image before upload
$("#imageUpload").change(function(){
var file = this.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(e){
$("#preview").html("<img src='" + e.target.result + "' alt='Preview'/>");
};
reader.readAsDataURL(file);
}
});
// Add image to gallery
$("#uploadForm").submit(function(e){
e.preventDefault();
var file = $("#imageUpload").get(0).files[0];
if (file) {
var reader = new FileReader();
reader.onload = function(e){
var gallery = [];
if (localStorage.getItem("pp-gallery")) {
gallery = JSON.parse(localStorage.getItem("pp-gallery"));
}
gallery.push(e.target.result);
localStorage.setItem("pp-gallery", JSON.stringify(gallery));
// Check if image URL exists before displaying
$.get(e.target.result).done(function() {
$(".gallery").prepend("<img src='" + e.target.result + "' alt='Image " + gallery.length + "'/>");
}).fail(function() {
console.log("Image URL does not exist: " + e.target.result);
});
$("#preview").html("");
};
reader.readAsDataURL(file);
}
});