This commit is contained in:
68
03_dom/uebungen/u10_running-lights/assets/js/main-ersin.js
Normal file
68
03_dom/uebungen/u10_running-lights/assets/js/main-ersin.js
Normal file
@@ -0,0 +1,68 @@
|
||||
'use strict';
|
||||
|
||||
(() => {
|
||||
const $ = (qs) => document.querySelector(qs);
|
||||
const $$ = (qs) => Array.from(document.querySelectorAll(qs));
|
||||
|
||||
// === DOM & VARS =======
|
||||
const DOM = {
|
||||
// Alle Glühbirnen-Bilder auswählen
|
||||
bulbs: $$('.light-bulbs img'),
|
||||
};
|
||||
|
||||
const LIGHT_PATH_ON = 'assets/img/light_on.png';
|
||||
const LIGHT_PATH_OFF = 'assets/img/light_off.png';
|
||||
|
||||
// Zähler
|
||||
let activeIndex = 0;
|
||||
|
||||
// === INIT =============
|
||||
const init = () => {
|
||||
if (DOM.bulbs.length === 0) return;
|
||||
|
||||
// zustand reseten
|
||||
updateLights(); // first bulb on
|
||||
|
||||
DOM.bulbs.forEach((bulb, index) => {
|
||||
bulb.addEventListener('mouseenter', (e) => onBulbHover(e, index));
|
||||
|
||||
bulb.addEventListener('click', onBulbClick);
|
||||
});
|
||||
};
|
||||
|
||||
// === EVENTHANDLER =====
|
||||
|
||||
const onBulbHover = (e, hoveredIndex) => {
|
||||
if (hoveredIndex === activeIndex) {
|
||||
nextLight();
|
||||
}
|
||||
};
|
||||
|
||||
const onBulbClick = () => {
|
||||
nextLight();
|
||||
};
|
||||
|
||||
// === FUNCTIONS ========
|
||||
|
||||
const nextLight = () => {
|
||||
activeIndex++;
|
||||
|
||||
if (activeIndex >= DOM.bulbs.length) {
|
||||
activeIndex = 0;
|
||||
}
|
||||
|
||||
updateLights();
|
||||
};
|
||||
|
||||
const updateLights = () => {
|
||||
DOM.bulbs.forEach((bulb, index) => {
|
||||
if (index === activeIndex) {
|
||||
bulb.src = LIGHT_PATH_ON;
|
||||
} else {
|
||||
bulb.src = LIGHT_PATH_OFF;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
init();
|
||||
})();
|
||||
Reference in New Issue
Block a user