Skip to content

Instantly share code, notes, and snippets.

@ijurko
Created August 30, 2024 13:04
Show Gist options
  • Save ijurko/d9696a2a19ca9580a32ed301b7f4928b to your computer and use it in GitHub Desktop.
Save ijurko/d9696a2a19ca9580a32ed301b7f4928b to your computer and use it in GitHub Desktop.
import { gsap } from "gsap";
/**
* Hotspot class for handling hotspot related functionality.
*/
export default class Hotspot {
/**
* Constructor for the Hotspot class.
* Initializes the DOM selectors and hotspots.
*/
constructor() {
/**
* DOM selectors
*/
this.DOM = {
hotspot: ".js-hotspot",
trigger: ".js-hotspot-trigger",
dialog: ".js-hotspot-dialog",
states: {
active: "is-active",
},
};
this.hotspots = document.querySelectorAll(this.DOM.hotspot);
}
/**
* Initializes the hotspots.
* If there are hotspots, it sets them up.
*/
init() {
if (this.hotspots.length > 0) {
this.hotspots.forEach((hotspot) => {
this.setup(hotspot);
});
}
}
/**
* Sets up a hotspot.
* @param {Element} hotspot - The hotspot to set up.
*/
setup(hotspot) {
const trigger = hotspot.querySelector(this.DOM.trigger);
const dialog = hotspot.querySelector(this.DOM.dialog);
if (trigger == null || dialog == null) {
return;
}
trigger.addEventListener("click", () => {
this.toggle(hotspot, dialog);
});
//click outside
document.addEventListener("click", (e) => {
if (!hotspot.contains(e.target) && hotspot.classList.contains(this.DOM.states.active)) {
this.close(hotspot, dialog);
}
});
}
/**
* Toggles a hotspot.
* If the hotspot is active, it closes it. Otherwise, it opens it.
* @param {Element} hotspot - The hotspot to toggle.
* @param {Element} dialog - The dialog of the hotspot.
*/
toggle(hotspot, dialog) {
if (hotspot.classList.contains(this.DOM.states.active)) {
this.close(hotspot, dialog);
} else {
this.open(hotspot, dialog);
}
}
/**
* Closes a hotspot.
* @param {Element} hotspot - The hotspot to close.
* @param {Element} dialog - The dialog of the hotspot.
*/
close(hotspot, dialog) {
gsap.to(dialog, {
autoAlpha: 0,
y: 10,
duration: 0.3,
onComplete: () => {
hotspot.classList.remove(this.DOM.states.active);
dialog.close();
},
});
}
/**
* Opens a hotspot.
* @param {Element} hotspot - The hotspot to open.
* @param {Element} dialog - The dialog of the hotspot.
*/
open(hotspot, dialog) {
hotspot.classList.add(this.DOM.states.active);
dialog.show();
gsap.fromTo(
dialog,
{
autoAlpha: 0,
y: 10,
},
{
autoAlpha: 1,
y: 0,
duration: 0.4,
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment