oldoc63 / learningFS

Web development back and front
0 stars 0 forks source link

Event Handler Registration #856

Open oldoc63 opened 2 years ago

oldoc63 commented 2 years ago

eventTarget.addEventListener('click', function() { // this block of code will run when click event happens on eventTarget element });


- Let’s break this down! 
  - We selected our event target from the DOM using document.getElementById('targetElement'). 
  - We used the .addEventListener() method on the eventTarget DOM element.
  - The .addEventListener() method takes two arguments: an event name in string format and an event handler function.
  - In this example, we used the 'click' event, which fires when the user clicks on eventTarget.
  - The code block in the event handler function will execute when the 'click' event is detected.

- Instead of using an anonymous function as the event handler, it’s best practice to create a named event handler function. Your code will remain organized and reusable this way, even if your code gets complex. Check out the syntax:

function eventHandlerFunction() { // this block of code will run when click event happens }

eventTarget.addEventListener('click', eventHandlerFunction);


- The named function eventHandlerFunction is passed as the second argument of the .addEventListener() method instead of defining an anonymous function within the method!
oldoc63 commented 2 years ago
  1. Look at the browser and notice that there are two elements, one containing informational text about JavaScript and a button. When the button is clicked, there should be more text that appears. Currently, clicking the button doesn’t seem to do anything. You are going to create an event handler to fix this!
  2. First, create a function called showInfo() which we will use as the event handler function to make the hidden element containing the additional informational text (moreInfo) appear when the 'click' event fires.
  3. Inside the function, create a statement that changes the .display style property of the moreInfo element to 'block'.
  4. Now, create an event handler for a click event using .addEventListener(). Use readMore as the event target and showInfo as the event handler function.
  5. Run your code and fire your event once you’re done.