sutty-base-jekyll-theme/_packs/controllers/slider_controller.js

74 lines
1.6 KiB
JavaScript
Raw Normal View History

2021-11-22 17:51:50 +00:00
import { Controller } from "stimulus";
2021-01-12 16:35:23 +00:00
/*
* Slider con scroll automático
*/
export default class extends Controller {
2021-11-22 17:51:50 +00:00
static targets = ["control"];
2021-01-12 16:35:23 +00:00
2021-11-22 17:51:50 +00:00
connect() {
this.active(
this.controlTargets.find((x) => x.href.endsWith(window.location.hash))
);
2021-01-12 16:35:23 +00:00
2021-11-22 17:51:50 +00:00
this.interval = setInterval(
() => (this.inViewport ? this.controlTargets[this.next].click() : null),
this.duration * 1000
);
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
get duration() {
const duration = parseInt(this.data.get("duration"));
2021-01-12 16:35:23 +00:00
2021-11-22 17:51:50 +00:00
return isNaN(duration) ? 15 : duration;
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
disconnect() {
clearInterval(this.interval);
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
active(control) {
if (!control) return;
2021-01-12 16:35:23 +00:00
2021-11-22 17:51:50 +00:00
this.controlTargets.forEach((other) =>
other.classList.toggle("active", control.href === other.href)
);
this.current = this.controlTargets.indexOf(control);
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
activate(event) {
2021-01-12 16:35:23 +00:00
// XXX: En Firefox, el target del evento también puede ser el
// contenido del link :/
2021-11-22 17:51:50 +00:00
let t = event.target.href ? event.target : event.target.parentElement;
2021-01-12 16:35:23 +00:00
2021-11-22 17:51:50 +00:00
this.active(t);
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
get current() {
return parseInt(this.data.get("current")) || 0;
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
set current(value) {
this.data.set("current", value);
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
get next() {
const next = this.current + 1;
2021-01-12 16:35:23 +00:00
2021-11-22 17:51:50 +00:00
return this.controlTargets[next] ? next : 0;
2021-01-12 16:35:23 +00:00
}
2021-11-22 17:51:50 +00:00
get inViewport() {
2021-01-12 16:35:23 +00:00
const bounding = this.element.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
2021-11-22 17:51:50 +00:00
bounding.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <=
(window.innerWidth || document.documentElement.clientWidth)
2021-01-12 16:35:23 +00:00
);
2021-11-22 17:51:50 +00:00
}
2021-01-12 16:35:23 +00:00
}