Grouped Mouse Events

Watching groups of elements, and finding where events came from

How grouped events work

  • Create a function that runs some code
  • Find a group of elements on your page
  • Run the function when something happens to any of the elements
  • Use the event data to find which element was the trigger

Step One:
Create a function

We already know how to do this!

function crossOffItem(){
  console.log('cross the item off the list');
}

Step Two:
Find a group of elements

Here’s a new function called getElementsByClass:

function crossOffItem(){
  console.log('cross the item off the list');
}

var listItems = document.getElementsByClass('item');

Step Three:
Watch for an event

Use a loop to add a listener to every item

function crossOffItem(){
  console.log('cross the item off the list');
}

var listItems = document.getElementsByClass('item');

for( var counter=0; counter<listItems.length; counter++){
  listItems[i].addEventListener('click', crossOffItem);
}

Step Four:
Find the trigger element

function crossOffItem( event ){
  console.log('cross the item off the list');
  console.log( event.target );
}

var listItems = document.getElementsByClass('item');

for( var counter=0; counter<listItems.length; counter++){
  listItems[i].addEventListener('click', crossOffItem);
}

When I click an item, it shows in te console.

Step Five:
Add the completed class when clicked

function crossOffItem( event ){
  console.log('cross the item off the list');
  console.log( event.target );
  event.target.classList.add('complete');
}

var listItems = document.getElementsByClass('item');

for( var counter=0; counter<listItems.length; counter++){
  listItems[i].addEventListener('click', crossOffItem);
}

When I click an item, it gets crossed off!

Whoa there, hold up, this just got tricky!

Let’s use our debugger to step through this line by line.

function crossOffItem( event ){
  console.log('cross the item off the list');
  console.log( event.target );
  event.target.classList.add('complete');
  debugger;
}

var listItems = document.getElementsByClass('item');
debugger;

for( var counter=0; counter<listItems.length; counter++){
  listItems[i].addEventListener('click', crossOffItem);
  debugger;
}

And how does this loop thing actually work?

  • for is like a function, it groups lines of code
  • for requires a counter, a limit and a stepper
  • counter starts at 0
  • the limit is the length of listItems
  • the stepper goes up by 1 each time

Clean up your debuggers and logs

Let’s use our debugger to step through this line by line.

function crossOffItem( event ){
  event.target.classList.add('complete');
}

var listItems = document.getElementsByClass('item');

for( var counter=0; counter<listItems.length; counter++){
  listItems[i].addEventListener('click', crossOffItem);
}

What we learned

  • Finding a group of elements by class
  • Using a loop to go through a group
  • Using event data to identify an element

Loading...