simple carousel images
by fxi
HTML
<script src="https://cdn.jsdelivr.net/npm/@fxi/[email protected]/dist/el.umd.min.js"></script>
<div id='target'></div>
CSS
#target {
width: 600px;
height: 400px;
background: #fff;
}
JavaScript
const el = El.el;
const urls = ['https://placekitten.com/g/800/600', 'https://placekitten.com/g/900/450', 'https://placekitten.com/g/900/550'];
class Carousel {
constructor(target, urls) {
this._urls = urls;
this._el_target = target;
this.next = this.next.bind(this);
this.previous = this.previous.bind(this);
this.build();
this.next();
}
build() {
this._el_p = el('a', {
target: '#',
style: {
cursor: 'w-resize',
height: '100%',
flex: 1
},
on: ['click', this.previous]
})
this._el_n = el('a', {
target: '#',
style: {
cursor: 'e-resize',
height: '100%',
flex: 1
},
on: ['click', this.next]
})
this._el_i = el('span', {
style: {
position: 'absolute',
height: '1em',
top: '1em',
left: '1em',
padding: '5px',
backgroundColor: 'rgba(255,255,255,0.3)'
}
})
this._el_c = el('div', {
style: {
display: 'flex',
width: '100%',
height: '100%'
}
},
this._el_i,
this._el_p,
this._el_n
);
this._el_target.innerHTML = '';
this._el_target.appendChild(this._el_c);
}
next() {
let pos = this._urls.indexOf(this._cur) + 1;
if (pos > this._urls.length - 1) {
pos = 0;
}
this._pos = pos;
this._cur = this._urls[pos];
this.render();
}
previous() {
let pos = this._urls.indexOf(this._cur) - 1;
if (pos < 0) {
pos = this._urls.length - 1;
}
this._pos = pos,
this._cur = this._urls[pos];
this.render();
}
render() {
this.setImage();
this.updateCounter();
}
setImage() {
this._el_c.style.backgroundImage = `url(${this._cur})`
}
updateCounter() {
this._el_i.innerText = `${(this._pos || 0) + 1} / ${this._urls.length}`
}
}
const c = new Carousel(target, urls);