EVENT_DRIVEN CONCEPTS


        "
Learn my section Asynchronous before moving to this"

  • JavaScript is an event-driven programming language which inherently supports non-blocking operations.

  • Using JavaScript you can register code to specific events and that code will be executed once the event is emitted, enabling the seamless execution of asynchronous code without blocking other operations.


  • As simple as this example is, it illustrates well how JavaScript uses events to execute a set of commands. Since the browser is single-threaded, using synchronous programming in this example would freeze everything else in the page, which would make every web page extremely unresponsive and impair the web experience in general.

The browser manages a single thread to run the entire JavaScript code using an inner loop, commonly referred to as the event loop. The event loop is a single-threaded loop that the browser runs infinitely.


Every time an event is emitted, the browser adds it to an event queue. The loop will then grab the next event from the queue in order to execute the event handlers registered to that event. After all of the event handlers are executed, the loop grabs the next event, executes its handlers, grabs the next event etc.
  • Event Loop Cycle
    Event Loop Cycle


JavaScript Event Types


JavaScript events provide a dynamic interface to a webpage, adding interactivity to your page.

Ways of Using JavaScript Events


            WHAT IS EVENT ??

"Any actions that you perform or any occurrence on the browser is an event. Your page loads, you click on the page, you navigate the page, an error occurs; all of these are events. The system tells you about them and you can add responses to them if you choose to. There are a lot of events available in JavaScript that you can respond to."

  • JavaScript provides a feature called event handler that helps you to respond to the events. An event handler is a block of code, usually a user-defined JavaScript Function, that runs when the event fires. When we define this block of code, we say that we are registering an event handler. They are sometimes interchangeably called event listeners, but they are different from each other and work together. 

  • The event handlers listen for the event to happen and the event handler is the code that runs in response to the event happening. You can add event handlers with either single quotes or double-quotes.

       Ways of Using Web Events in JavaScript

              How events trigger JavaScript code???

        You can trigger JavaScript from HTML pages in three steps:

  • Select the element node(s) for which you want the JavaScript script to respond.
  • Indicate which event will trigger the response (binding event to the DOM node).
  • Define the code you want to execute when the event occurs.

     "Check my objects section before diving to it "

 1. Inline/HTML Event Handlers

  • This is bad-practice, but since you see it in older browsers, you need to be aware of it. This method is no longer in use; it is always better to separate the JavaScript from the HTML.
    <body>
    <button onclick = "changeColor()">Inline Event trigger</button> <!-- function call -->
    <p></p>
    <!-- JavaScript code -->
    </body> 

2. Traditional DOM Event Handlers

DOM event handlers, introduced in the original specification for the DOM, is an alternative to add an event handler to any element. This method separates JavaScript from the HTML, thus is preferred over Inline event handlers. All the major browsers support this approach. The drawback is that for any event, you can attach only one function. As a result, if a page uses more than one script, and both scripts respond to the same event, then one or both of the scripts may not work as intended

Syntax:   element.onclick = Eventlistener // event listener is a funtion name

3. addEventListener() and removeEventListener()

These are the favored way of adding an event handler, introduced in an update to the DOM (DOM level2, in the year 2000). Unlike traditional DOM event handlers, these allow a single event to trigger multiple functions with single element

For eg:

<script>
const button = document.querySelector('button')


const buttoneventhandeler = (event) => {
console.log('button clicked')
console.log(event);
   
// here we are passing "event as argument" is a Event Object 
With access to the event object, I can now also determinethe
type of the event that occurred (focus, blur, click, etc.)

Besides it gives access to different properties that is
triggered

The Event Objects Type Property
console.log(event.type)
console.log(event.clientX)
console.log(event.clientY)
console.log(event.offsetX)
console.log(event.offsetY) and many more ...

try it out in console



}

const buttoneventhandeler1 = (event) => {
console.log('button was clicked')
console.log(event);



}


button.addEventListener('click', buttoneventhandeler);
button.addEventListener('click', buttoneventhandeler1);
</script>


Output:

indexs.html:18 button clicked indexs.html:19 MouseEvent {isTrusted: true, screenX: 126, screenY: 213, clientX: 59, clientY: 86, …} indexs.html:26 button was clicked indexs.html:27 MouseEvent {isTrusted: true, screenX: 126, screenY: 213, clientX: 59, clientY: 86, …}


     PreventDefault method():

  • The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
  • You can stop browser from following its default behaviour and use our own logic.
<form action="">
<label for="title">Title</label>
<input type="text" id="title">
<button type="submit">submit</button>
</form>


const form = document.querySelector('form')
form.addEventListener('submit', (event) => {
event.preventDefault();
});

here page getsreloaded, becoz default beahviour of the form html elemnt combined with submit button is to send form data to the serverso that server serves
the page -->

let say you sometimes wants to prevent sending data to the serverwhen button is clicked instead you wanna a step in with javascript and maybe validate the userinputbefore you takeit and send with help of Js ,
how to send http request with js.so you might
wanna prevent default behaviour of the browser"V



   EVENT FLOW CONCEPTS:

There are two ways in which an event can function:

  • Event Bubbling
  • Event Capturing

Understanding these mechanisms will simplify what happens when event handlers are activated on an element.

Why the event flow matters?

The flow of events only really matters when the code has event handlers on both an element and one of its ancestor/descendant elements. If the Boolean value is true, it sets the capturing phase but if false, it is the bubbling phase.

capturing and bubbling phase - JavaScript Events

Event Bubbling

The event flows inside to outside

Event Capturing

The event flows  outside to inside


<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="css/event.css">
<style>
#box-1 {
background: red;
width: 400px;
height: 400px;
}
#box-2 {
background: gray;
width: 300px;
height: 300px;
}
#box-3 {
background: blue;
width: 200px;
height: 200px;
}
#box-4 {
background: green;
width: 100px;
height: 100px;
}
li {
padding: 1rem;
border: 1px solid gray;
}
ul {
list-style: none;
}
.highlight {
background-color: red;
}
</style>
</head>

<body>
<div id="box-1">1
<div id="box-2">2
<div id="box-3">3
<div id="box-4">4</div>
</div>
</div>
</div>
<script>

//False isthe bubbling phase default and true is capture phase
const div1 = document.getElementById('box-1')
const div2 = document.getElementById('box-2')
const div3 = document.getElementById('box-3')
const div4 = document.getElementById('box-4')

div1.addEventListener('click', event => {
console.log(event)
console.log(1)
},false/true)
div2.addEventListener('click', event => {
console.log(event)
console.log(2)
},false/true)
div3.addEventListener('click', event => {
console.log(event)
event.stopPropagation();
console.log(3)
},false/true)
div4.addEventListener('click', event => {
console.log(event)
console.log(4)

event.stopPropagation();
// if we have multiple eventlisteners on same event add
event.stopImmediatePropagation();
},false/true) -
the event just not trigger on element itself but also on ancestors that called propogation, means it bubbles of or kind of caputure (from outside to inside)

STOPPROPAGATION():

Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
--- we can prevent this clicked at div4 only trigger itself not up its element.----


The stopImmediatePropagation() method of the Event interface
 prevents other listeners of the same event from being called.

If several listeners are attached to the same element for the same event type,
they are called in the order in which they were added.
If stopImmediatePropagation() is invoked during one such call, no remaining listeners will be called.

</script>
</body>



Some topics must be known:

use of scrolling events

window.addEventListener('scroll', (event) => {
console.log(event);}



Javascript events:

These are the top 8 types of JavaScript Event discussed below:

1. User Interface events

These occur as the result of any interaction with the browser window rather than the HTML page. In these events, we attach the event listener to the window object, not the document object. The various UI events are as follows.

  • load

The load event fires when the webpage finishes loading. It can also fire on nodes of elements like images, scripts, or objects.

  • unload

This event fires before the users leave the page, i.e., the webpage is unloading. Page unloading usually happens because a new page has been requested.

  • error

This event fires when the browser encounters a JavaScript error or an asset that doesn’t exist.

  • resize

It fires when we resize the browser window. But browsers repeatedly fire this event, so avoid using this event to trigger complicated code; it might make the page less responsive.

  • scroll

This event fires when the user scrolls up/down on the browser window. It can relate to the entire page or a specific element on the page.



2. Focus and blur events

These events fire when the HTML elements you can interact with gain/ lose focus. They are most commonly used in forms and especially helpful when you want to do the following tasks:

  • To show tips or feedback to users as they interact with an element within a form. The tips are usually shown in the elements other than the one the user is interacting with.

  • To trigger form validation as a user moves from one control to the next without waiting to submit the form.

The different focus and blur events are as follows:

  • focus

This event fires, for a specific DOM node, when an element gains focus.

  • blur

This fires, for a specific DOM node, when an element loses focus.

  • focusin

This event is the same as the focus event. But Firefox doesn’t yet support the focusin event.

  • focusout

This is the same event as the blur event. This is a new event type in JavaScript, thus not supported in Firefox right now.

The focus and blur events use the capture approach, while the focusin and focusout events use both capture and bubble approach of the event flow.




3. Mouse events

These events fire when the mouse moves or the user clicks a button. All the elements of the page support these events and use the bubbling approach. These actions work differently on touchscreen devices. Preventing the default behavior of mouse events can cause unexpected results. The various mouse events of JavaScript are as follows:

  • click

This event fires when the user clicks on the primary mouse button (usually the left button). This event also fires if the user presses the Enter key on the keyboard when an element has focus.

Touch-screen: A tap on the screen acts like a single left-click.

  • dblclick

This event fires when the user clicks the primary mouse button, in quick succession, twice.

Touch-screen: A double-tap on the screen acts like a double left-click.

Accessibility: You can add the above two events to any element, but it’s better to apply it only on the items that are usually clicked, or it will not be accessible through keyboard navigation. All the mouse events discussed below cannot be triggered by the keyboard.

  • mousedown

It fires when the user clicks down on any mouse button.

Touch-screen: You can use the touchstart event.

  • Mouseup

It fires when the user releases a mouse button.

Touch-screen: You can use the touchend event.

We have separate mousedown and mouseup events to add drag-and-drop functionality or controls in game development. Don’t forget a click event is the combination of mousedown and mouseup events.

  • mouseover

It fires when the user moves the cursor, which was outside an element before, inside the element. We can say that it fires when we move the cursor over the element.

  • mouseout

It fires when the user moves the cursor, which was inside an element before, outside the element. We can say that it fires when the cursor moves off the element.

The mouseover and mouseout events usually change the appearance of graphics on our webpage. A prefered alternative to this is to use the CSS: hover pseudo-class.

  • mousemove

It fires when the user moves the cursor around the element. This event is frequently triggered.

This is the right time to learn about JavaScripts Loops. MUST CHECK!!



4. Keyboard events

These events fire on any kind of device when a user interacts with a keyboard.

  • input

This event fires when the value of an <input> or a <textarea> changes (doesn’t fire for deleting in IE9). You can use keydown as a fallback in older browsers.

  • keydown

It fires when the user presses any key in the keyboard. If the user holds down the key, this event fires repeatedly.

  • keypress

It fires when the user presses a key that results in printing a character on the screen. This event fires repeatedly if the user holds down the key. This event will not fire for the enter, tab, or arrow keys; the keydown event would.

  • keyup

The keyup event fires when the user releases a key on the keyboard.

The keydown and keypress events fire before a character appears on the screen, the keyup fires after it shows.

To know the key pressed when you use the keydown and keypress events, the event object has a keyCode property. This property, instead of returning the letter for that key, returns the ASCII code of the lowercase for that key.

5. Form events

These events are common while using forms on a webpage. In particular, we see the submit event mostly in form of validation (checking form values). As described in our tutorial; Features of JavaScript, if the users miss any required information or enter incorrect input, validation before sending the data to the server is faster. The list below explains the different form of events available to the user.

  • submit

This event fires on the node representing the <form> element when a user submits a form.

  • change

It fires when the status of various form elements change. This is a better option than using the click event because clicking is not the only way users interact with the form.

  • input

The input event is very common with the <input> and the <textarea> elements.

We often use the focus and blur events with forms, but they are also available in conjunction with other elements like links.



6. Mutation events and observers

  • Whenever the structure of the DOM tree changes, it triggers a mutation event. The change in the tree may be due to the addition or removal of a DOM node through your script. But these have an alternative that will replace them: mutation observers. The following are the numerous mutation events in JavaScript.

  • DOMNodeInserted

It fires when the script inserts a new node in the DOM tree using appendChild(), replaceChild(), insertBefore(), etc.

  • DOMNodeRemoved

This event fires when the script removes an existing node from the tree using removeChild(), replaceChild(), etc.

  • DOMSubtreeModified

It fires when the structure of the DOM tree changes i.e. the above two events occur.

  • DOMNodeInsertedIntoDocument

This event fires when the script inserts a node in the DOM tree as the descendant of another node already in the document.

  • DOMNodeRemovedFromDocument

This event fires when the script removes a node from the DOM tree as the descendant of another node already in the document.

The problem with the mutation events is that lots of changes to your page can make your page feel slow or unresponsive. These can also trigger other event listeners, modifying DOM and leading to more mutation events firing. This is the reason for introducing mutation observers to the script.

Mutation observers wait until the script finishes its current task before reacting, then reports the changes in a batch (not one at a time). This reduces the number of events that fire when you change the DOM tree through your script. You can also specify which changes in the DOM you want them to react to.



7. HTML5 events

These are the page-level events included in the versions of the HTML5 specialization. New events support more recent devices like phones and tablets. They respond to events such as gestures and movements. You will understand them better after you master the above concepts, thus they are not discussed for now. Work with the events below for now and when you are a better developer, you can search for other events available. The three HTML5 events we will learn are as follows:

  • DOMContentLoaded

This event triggers when the DOM tree forms i.e. the script is loading. Scripts start to run before all the resources like images, CSS, and JavaScript loads. You can attach this event either to the window or the document objects.

  • hashchange

It fires when the URL hash changes without refreshing the entire window. Hashes (#) link specific parts (known as anchors) within a page. It works on the window object; the event object contains both the oldURL and the newURL properties holding the URLs before and after the hashchange.

  • beforeunload

This event fires on the window object just before the page unloads. This event should only be helpful for the user, not encouraging them to stay on the page. You can add a dialog box to your event, showing a message alerting the users like their changes are not saved.



8. CSS events

  • These events trigger when the script encounters a CSS element. As CSS is a crucial part of web development, the developers decided to add these events to js to make working with CSS easier. Some of the most common CSS events are as follows:

  • transitionend

This event fires when a CSS transition ends in a program. It is useful to notify the script of the end of transition so that it can take further action.

  • animationstart

These events fire when CSS animation starts in the program.

  • animationiteration

This event occurs when any CSS animation repeats itself. With this event, we can determine the number of times an animation iterates in the script.

  • animationend

It fires when the CSS animation comes to an end in the program. This is useful when we want to act just after the animation process finishes.



EVENT DELEGATION CONCEPT:










DRAG DROP EVENTS:

Comments

Popular posts from this blog

JavaScript — Double Equals vs. Triple Equals - weird things on JavaScript

06_Understanding Execution Context and Execution Stack in Javascript

Creating and inserting element- part-2