Code Monkey home page Code Monkey logo

phase-0-javascript-events-event-listening-lab's Introduction

JavaScript Event Listeners Lab

Learning Goals

  • Create event listeners on DOM nodes using addEventListener()

Introduction

In this lab we will learn how to teach nodes to "listen" for an event using addEventListener().

If you haven't already, fork and clone this lab into your local environment. Navigate into its directory in the terminal, then run code . to open the files in Visual Studio Code.

Create Event Listeners on DOM Nodes with addEventListener()

In order for JavaScript to handle an event, we first need to tell it to listen for that event. We do this by calling the addEventListener() method on the element we want to add the listener to, and passing it two arguments:

  1. the name of the event to listen for, and
  2. a callback function to "handle" the event

Open up index.html in the browser. When you click in the <input> area, nothing happens. Let's set up some event handling. Specifically, let's add an event listener for the click event on the input#button element in index.html.

Try out the following in the Chrome DevTools console:

const input = document.getElementById('button');
input.addEventListener('click', function() {
  alert('I was clicked!');
});

Now when you click inside of input#button, you will get an alert box.

Let's review what's happening in this code.

First, we grab the element that we want to add the event listener to and save a reference to it in the input variable.

Next, we call addEventListener() on that element to tell JavaScript to listen for the event. We pass two arguments to addEventListener(): the name of the event to listen for (in this case, click) and a callback function that will be executed when the event is "heard."

According to MDN:

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

That's exactly what's happening here: we're passing a callback function as the second argument to the addEventListener() function; the callback will be invoked as soon as the event occurs.

Let's pull out that second argument and take a look at it:

function() {
  alert('I was clicked!');
}

This function has all the components of functions we've seen before (the function keyword, a pair of parentheses, and the body of the function enclosed in curly braces) except one: it doesn't have a name assigned to it. This is what's called an anonymous function. Because it doesn't have a name, it can't be invoked directly. But the event listener knows to execute whatever function is passed as the second argument when it detects the event, so it doesn't need to be named.

If we are only calling our callback function in that one place, using an anonymous function makes sense. However, what if we wanted to use that same alert message on a bunch of elements? In that case, it would make more sense to create a separate, named function that could be called by all of our event listeners. With this approach, we would pass the function name as the second argument to addEventListener() rather than the function itself:

const input = document.getElementById('button');

function clickAlert() {
  alert('I was clicked!');
}

input.addEventListener('click', clickAlert);

We could then attach our clickAlert to as many elements as we'd like. Just as we did for the input element, we would first use our CSS selector skills to grab the desired element and save it to a variable, then add the click event listener to that element. Give it a try!

With this approach, even if we're using our clickAlert with a whole bunch of elements, if we decide later that we want to change the text of the alert to "Hee hee, that tickles!" instead, we would only need to make that change in one place: inside our clickAlert() function.

Note: we pass clickAlert as the argument, not clickAlert(). This is because we don't want to invoke the function in this line of code. Instead, we want to pass a reference to the function to addEventListener() so it can call the function when the time comes.

Refresh your browser and try out the latest version of the code in the console to verify that it works. Also try passing clickAlert() as the second argument rather than clickAlert and see what happens.

Passing the Tests

Now let's set up index.js to do the same thing so we can get our test passing. To do that, simply copy the code into the index.js file's addingEventListener() function and run the test. Either version should pass the test โ€” just make sure that the code creating the event listener is inside the addingEventListener() function.

Checking the Code in the Browser

We know that the code works in the console and passes the test, but we should also check our changes to index.js in the browser. Because you've added the addEventListener() function inside the addingEventListener() function, recall that you will need to call the outer function in index.js to execute addEventListener() and activate the event listener. Be sure to refresh the page to load the new code in index.js.

Resources

phase-0-javascript-events-event-listening-lab's People

Contributors

dependabot[bot] avatar drakeltheryuujin avatar graciemcguire avatar ihollander avatar jenmyers avatar jlboba avatar lizbur10 avatar maxwellbenton avatar professor-ben avatar sgharms avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phase-0-javascript-events-event-listening-lab's Issues

addingEventListener() doesn't allow 'click' event to run

Canvas Link

https://learning.flatironschool.com/courses/5639/assignments/179041?confetti=true&submitted=0

Concern

Code:

function addingEventListener() {
    const input = document.getElementById('button');

    input.addEventListener('click', () => {
        document.getElementsByTagName('div')[1].remove();
    });
}

The above code doesn't run in the browser. However, removing the nested code from the addingEventListener() function allows it to run successfully.

Additional Context

No response

Suggested Changes

No response

npm test results are broken.

Thanks for raising this issue! Future learners thank you for your diligence. In
order to help the curriculum team address the problem, please use this template
to submit your feedback. We'll work on addressing the issue as soon as we can.

Please fill out as much of the information below as you can (it's ok if you
don't fill out every section). The more context we have, the easier it will be
to fix your issue!

Note: you should only raise issues related to the contents of this lesson.
If you have questions about your code or need help troubleshooting, reach out to
an instructor/your peers.


Link to Canvas

Add a link to the assignment in Canvas here.

Describe the bug

initial npm test results in this:

$ npm test

[email protected] test
mocha --timeout 5000 -R mocha-multi --reporter-options spec=-,json=.results.json

  1. "before all" hook

0 passing (7s)
1 failing

  1. "before all" hook:
    Error: Timeout of 5000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
    at Object.done (node_modules/mocha-jsdom/index.js:70:7)
    at /mnt/d/Programming/FlatironSchool/code/phase0/phase-0-javascript-events-event-listening-lab/node_modules/jsdom/lib/jsdom.js:312:18
    at processTicksAndRejections (node:internal/process/task_queues:78:11)

Write a clear and concise description of what the bug is. Include the file and
line number(s) if possible.

What is the expected behavior?

Write a clear and concise description of what you expected to happen.

Screenshots

If applicable, attach screenshots to help explain your problem.

What OS are you using?

  • OS X
  • WSL
  • Linux

Any additional context?

Add any other context about the problem here.

Phrasing of "hook up elements to callbacks" seems backwards

Canvas Link

https://learning.flatironschool.com/courses/5185/assignments/179292?module_item_id=396166

Concern

This phrasing seems backwards:
We could then hook up as many elements as we'd like to our clickAlert.

It seems like we are able to attach our cool function to lots of different elements/events rather than attach events to the function. Is this saying that under the covers, the clickAlert function object maintains a list of all the elements it is hooked to?

Additional Context

No response

Suggested Changes

Instead of this:
We could then hook up as many elements as we'd like to our clickAlert.

it seems like the flow is more like:
We could then hook up our clickAlert function to as many elements as we'd like.

Are the callbacks attached to elements or to events?
If I'm missing this, maybe a deeper explanation is needed. :-)

Difference in the Id Name

In the lesson in Canvas the code includes const input = document.getElementById("button") and instructs students to copy & paste the code into the console in the browser and VS Code in order to pass the test. However, the button's Id is "input" in index.html, not "button" so an error pops up. Not sure if this is intentional or not, but wanted to flag it just in case.

Incorrect element id referenced in code snippet in Canvas

Canvas Link

https://my.learn.co/courses/355/assignments/16574?module_item_id=38484

Concern

Canvas references element id "input" in code snippet and elsewhere. The correct element id is "button". It's referenced correctly in the readme.md in GitHub for this lesson.

Now when you click inside of input#input, you will get an alert box. Should be input#button

Additional Context

No response

Suggested Changes

const input = document.getElementById('button');

Incorrect getElementById Element for test code

Canvas Link

https://learning.flatironschool.com/courses/5292/assignments/179703?module_item_id=396882

Concern

The input element is input#input, not input#button, when you copy and paste the provided code from the first code block it returns an error in Chrome DevTools console... unless you switch getElementById to:

const input = document.getElementById('input');

Additional Context

No response

Suggested Changes

const input = document.getElementById('input');
input.addEventListener('click', function() {
alert('I was clicked!');
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.