JSFiddle - React, Tailwind, and code Playground
by JessOtto
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Image gallery</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Image gallery example</h1>
<div class="full-img">
<img class="displayed-img" src="images/pic1.jpg">
<div class="overlay"></div>
<button class="dark">Darken</button>
</div>
<div class="thumb-bar"></div>
<script src="main.js"></script>
</body>
</html>
CSS
h1 {
font-family: helvetica, arial, sans-serif;
text-align: center;
}
body {
width: 640px;
margin: 0 auto;
}
.full-img {
position: relative;
display: block;
width: 640px;
height: 480px;
}
.overlay {
position: absolute;
top: 0;
left: 0;
width: 640px;
height: 480px;
background-color: rgba(0,0,0,0);
}
button {
border: 0;
background: rgba(150,150,150,0.6);
text-shadow: 1px 1px 1px white;
border: 1px solid #999;
position: absolute;
cursor: pointer;
top: 2px;
left: 2px;
}
.thumb-bar img {
display: block;
width: 20%;
float: left;
cursor: pointer;
}
JavaScript
const displayedImage = document.querySelector('.displayed-img');
const thumbBar = document.querySelector('.thumb-bar');
const btn = document.querySelector('button');
const overlay = document.querySelector('.overlay');
/* Looping through images */
for (var i = 1; i <= 5; i++) {
let xxx = "images/pic" + i + ".jpg";
const newImage = document.createElement('img');
newImage.setAttribute('src', xxx);
thumbBar.appendChild(newImage);
}
function changeMainImg(e) {
let attri = e.target.src;
if (overlay.innerHTML === '') {
const newImage = document.createElement('img');
newImage.setAttribute('src', attri);
overlay.appendChild(newImage);
} else {
overlay.innerHTML = '';
const newImage = document.createElement('img');
newImage.setAttribute('src', attri);
overlay.appendChild(newImage);
}
};
thumbBar.addEventListener('click', changeMainImg);
/* Wiring up the Darken/Lighten button */
function darkenImage() {
let attri = btn.getAttribute('class');
//console.log(attri);
if (attri === "dark") {
btn.setAttribute('class', 'light');
btn.textContent = 'Lighten';
overlay.style.backgroundColor = "rgba(0,0,0,0.5)";
//console.log(attri);
} else {
btn.setAttribute('class', 'dark');
btn.textContent = 'Darken';
overlay.style.backgroundColor = "rgba(0,0,0,0)";
//console.log(attri);
}
};
btn.addEventListener('click', darkenImage);