Instantly share code, notes, and snippets.

Embed
What would you like to do?
Slider
<style>
.gallery {
list-style: none;
padding: 0;
}
.gallery li {
display: inline-block;
}
.gallery li img {
max-width: 120px;
}
.slider {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.75);
z-index: 40;
padding: 20px;
display: flex;
}
.slider .full {
margin: auto;
max-width: 100%;
max-height: 100%;
display: block;
}
.slider button {
flex: 0;
position: fixed;
top: 0;
bottom: 0;
width: 50%;
border: none;
background: none;
}
.slider button.next {
right: 0;
}
.slider button.previous {
left: 0;
}
.slider button.close {
right: 0;
bottom: initial;
background: white;
color: black;
width: auto;
}
</style>
<ul class="gallery">
<li>
<a href="https://media.balandavid.com/david-balan/article/Full-frame-less/high.jpg">
<img src="https://media.balandavid.com/david-balan/article/Full-frame-less/thumb.jpg" alt="May the force be with you">
</a>
</li>
<li>
<a href="https://media.balandavid.com/david-balan/article/DSCF0145/high.jpg">
<img src="https://media.balandavid.com/david-balan/article/DSCF0145/thumb.jpg" alt="Lego batman">
</a>
</li>
<li>
<a href="https://media.balandavid.com/david-balan/article/cake-logo/high.png">
<img src="https://media.balandavid.com/david-balan/article/cake-logo/thumb.png" alt="">
</a>
</li>
</ul>
<script>
const $ = (s, c=document) => c.querySelector(s),
$$ = (s, c=document) => c.querySelectorAll(s),
a = n => Array.from(n),
c = (t, a, i) => {
t = document.createElement(t);
a && Object.keys(a).forEach((k) => { t[k] = a[k]; });
i && i.appendChild(t);
return t;
}
let images, main_position, slider;
const create = () => {
slider = c('div', {className: 'slider'}, $('body'));
c('img', {className: 'full'}, slider);
const next = c('button', {className: 'next', innerHTML: '>'}, slider),
previous = c('button', {className: 'previous', innerHTML: '<'}, slider),
close = c('button', {className: 'close', innerHTML: 'X'}, slider);
next.addEventListener('click', e => e.stopPropagation() || showImage(images, main_position + 1));
previous.addEventListener('click', e => e.stopPropagation() || showImage(images, main_position - 1));
close.addEventListener('click', e => e.stopPropagation() || (slider.style.display='none'));
},update = () => {
if(!slider) {
create();
}
$('.full', slider).src = images[main_position].href;
slider.style.display='flex';
},showImage = (list, position=0) => {
images = list;
main_position = position >= images.length ? 0 : position < 0 ? images.length - 1 : position;
update();
}
a($$('.gallery')).forEach(elm => {
const links = a($$('a', elm));
links.forEach((a, i) => {
a.addEventListener('click', (e) => {
e.preventDefault();
showImage(links, i);
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment