Event Loop
Hier diesen Teil einfügen!
- Watch What the heck is the event loop anyway? by Philip Roberts
const buttonOne = document.querySelector('.btn-one');const buttonTwo = document.querySelector('.btn-two');
// button is the listening elementbuttonOne.addEventListener('click', e => { buttonOne.style.backgroundColor = 'lightseagreen'; // get information about the event: console.log(e); // get information about the target: console.log(e.currentTarget);});
// create a separate function// function changeButtonColor(e) {// buttonTwo.style.backgroundColor = 'midnightblue';// buttonTwo.style.color = 'white';// }// 1) use the "this" keyword// it refers to the listening element// function changeButtonColor(e) {// console.log(this);// this.style.backgroundColor = 'midnightblue';// this.style.color = 'white';// }// 2) use currentTargetfunction changeButtonColor(e) { e.currentTarget.style.backgroundColor = 'midnightblue'; e.currentTarget.style.color = 'white';}// buttonTwo has to be defined before the function is used, wouldn't work otherwisebuttonTwo.addEventListener('click', changeButtonColor);
// Event Listeners will listen to the capturing phase when provided with a third argument, useCapture.// If useCapture is true, the event will be called in the capturing phase.// Element.addEventListener('event-name', callback, useCapture);
const boxes = Array.from(document.querySelectorAll('.box'));
boxes.forEach(box => { box.addEventListener( 'click', e => { console.log(e.eventPhase, e.currentTarget); // e.stopPropagation(); } );});
// click button five times and then remove the event listenerconst btn = document.querySelector('.btn-one');
function clickFive(e) { const elem = e.currentTarget; const prevCount = parseInt(elem.dataset.count) || 0; const currentCount = prevCount + 1; elem.dataset.count = currentCount;
console.log(`The button was clicked ${currentCount} times!`);
if (currentCount === 5) { elem.removeEventListener('click', clickFive); };};
btn.addEventListener('click', clickFive);