Thursday, December 12, 2019

Module 5: targets, bubbling, propagation and capture

The event object.
To access it we modify our callback, our handler, we modify it to accept a parameter.

function handleBuyButtonClick(event) {
   console.log('You are buying it!');
  console.log('event');
}

buyButtons.forEach(function(buyButton) {
   buyButton.addEventListener('click', handleButtonClick);
});

//// the same but different

function handleBuyButtonClick(event) {
   console.log('You are buying it!');
  console.log('event.target'); // with that it will show you which button was clicked. // you can access anything about that event using event.target
}

//So if you want to see the TextContent inside the button that was clicked:
Add
const button = event.target;
inside the function, then
console.log(button.textContent);

buyButtons.forEach(function(buyButton) {
   buyButton.addEventListener('click', handleButtonClick);
});

////the same but different

For this to work you first have to add data-price="x-amount of dollars" to the html.

function handleBuyButtonClick(event) {
   console.log('You are buying it!');
  console.log('event.target.dataset.price'); // with that it will show you which button was clicked. //wrap it with parseFloat() to get a number since the regular output is a string.
}

buyButtons.forEach(function(buyButton) {
   buyButton.addEventListener('click', handleButtonClick);
});

//

another way is to use event.currentTarget
console.log(event.currentTarget);

What is the difference?
Are they the same?
The difference comes when you have nested elements.

In most cases you want to use event.currentTarget
to be precise.

Clicking on multiple things at once:
PROPAGATION

if you want to stop propagation

event.stopPropagation();

///

window.addEventListener('click', function(event) {
console.log(event.target);
});

//

There is a way to flip that.
capture:

window.addEventListener('click', function(event) {
console.log(event.target);
}, { capture: true });

//

photoEl.addEventListener('mousemove', function(e) {
   console.count(e.currentTarget);
});

photoEl.addEventListener('mouseenter', function(e) {
   console.count(e.currentTarget);
});


//


photoEl.addEventListener('mouseenter', function(e) {
   console.count(e.currentTarget);
   console.count(this);
});
//look to the left of the dot.



No comments:

Post a Comment

Arrays 4 : Callback Methods find() filter() some() every() sort()

  /* Callback Methods */ // const util = { // findBurgRating: function(singleFeedback) { // return singleFeedback.comment....