Event-Driven Programming

Event-Driven Programming

Event-Driven JavaScript

It basically implies performing some action based on user action. This action can be anything for example scrolling, clicking etc

Creating An Event

Syntax : element.EventListener('type of event that we want to listen to", callback function to be called when that event occurs)

Behaviour Of this

this will always be linked to the element which is written before the event listener div.EventListener('type of event that we want to listen to", callback function to be called when that event occurs) Here this will point to the div as it is written before the eventListener method

Propagation Of An Event

In event propagation what we basically try to understand is the order in which the different events will be executed or called in. Event propagation becomes very important when we have multiple event listeners on different tags and we are trying to understand in which order they will get executed Whenever an event occurs it will propagate through the DOM in the following ways.

  1. Capturing
  2. Target
  3. Bubbling

Capturing Phase: This will happen when we are moving from the root of the HTML to the element that we are targetting. This will happen only when the user has performed the event that we are listening for.

Target Phase: This is when we reach the target element and then the necessary callback function is called.

Bubbling Phase: This happens when we have reached the target element and are moving back towards the root.If we have any event listeners added when we are moving upwards all of them will get fired irrespective o the fact that the user has made those actions are not

How Does Event Bubbling help us?

Let us Consider an Example

Screenshot 2022-10-27 160714.jpg

In the figure given above, we want something to happen when we click on any of the list items which are one, two, three,four

The brute force method would be to associate event handlers with all 4 items. By doing this we are increasing the Complexity and we will have to write more code which will increase the size making it difficult to debug

the smarter way will be to create and event handler with the parent that is ul , by which i mean is if any of the list items are clicked during the bubbling phase it will eventually reach the parent element and hence we are using it as our advantage by reducing the amount of code written.

Stopping The Propagation

We can manually stop the propagation by calling
event.StopPropagation()

Removing An Event Listener

The removeEventListener() method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. The event listener to be removed is identified using a combination of the event type, the event listener function itself, and various optional options that may affect the matching process; see Matching event listeners for removal.