feat: Add a menu class to game

Use event delegation and the data-action attribute.
This commit is contained in:
sthag 2026-04-04 11:17:54 +02:00
parent e698161a2d
commit aa40877469

View file

@ -113,25 +113,44 @@ tags:
const menu = document.querySelector('body > header'); const menu = document.querySelector('body > header');
const placeholder = document.querySelectorAll('.background'); const placeholder = document.querySelectorAll('.background');
menu.addEventListener('click', (event) => { class Menu {
const buttons = menu.querySelectorAll('button'); constructor(element) {
const buttonTarget = event.target.closest('button'); // this._elem = element;
element.addEventListener('click', this.onClick.bind(this)); // Bind to get the clicked element and not the DOM element of the class
if (buttonTarget && event.button === 0) {
for (button of buttons) {
button.classList.remove('active');
}
buttonTarget.classList.add('active');
} }
});
escape() {
console.log('escape');
}
previous() {
console.log('previous');
}
quest() {
console.log('quest');
}
onClick(event) {
console.debug(event.target);
const action = event.target.dataset.action;
const siblings = event.target.parentElement.querySelectorAll('button');
if (action && event.button === 0) {
for (const sibling of siblings) {
sibling.classList.remove('active');
}
event.target.classList.add('active');
this[action]();
}
};
}
placeholder.forEach(element => { placeholder.forEach(element => {
const hue = randomIntFrom(0, 360); const hue = randomIntFrom(0, 360);
const grayscale = randomFloatFrom(0, 1); const grayscale = randomFloatFrom(0, 1);
console.log(hue, grayscale);
new RandomPixelCanvas(element, { new RandomPixelCanvas(element, {
width: Math.floor(element.parentElement.clientWidth), width: Math.floor(element.parentElement.clientWidth),
height: Math.floor(element.parentElement.clientHeight), height: Math.floor(element.parentElement.clientHeight),
@ -139,5 +158,7 @@ tags:
filter: 'grayscale(' + grayscale + ') hue-rotate(' + hue + 'deg)' filter: 'grayscale(' + grayscale + ') hue-rotate(' + hue + 'deg)'
}); });
}); });
new Menu(menu);
</script> </script>
{% endblock %} {% endblock %}