EVENTS IN JAVASCRIPT

JSHTML events are “things” that happen to HTML elements. When JavaScript is used in HTML pages, it can “react” to these events.

EVENTS HTML

An HTML event can be something the browser does or something a user does. Here are some examples of HTML events:

  • An HTML web page has finished loading
  • An HTML input field has been changed
  • An HTML button was clicked

Often, when events happen, you may want to do something. JavaScript allows you to execute code when events are detected. HTML allows you to add event handler attributes, with JavaScript code, to HTML elements.

With single quotes:

<element event=some JavaScript>

With double quotes:

<element event=some JavaScript>

In the following example, an onclick (with code) attribute is added to a <button>

<button onclick=”document.getElementById(‘demo’).innerHTML = Date()“>The time is?</button>

In the example above, the JavaScript code changes the content of the element with id = “demo”. In the next example, the code changes the content of its element (using this.innerHTML):

<button onclick=”this.innerHTML = Date()“>The time is?</button>

JavaScript code is often several lines long. It is more common to see event attributes calling functions:

<button onclick=”displayDate()“>The time is?</button>

<script>

function displayDate() {

  document.getElementById(“demo”).innerHTML = Date();

}

</script>

Here is a list of some common HTML events:

Events

JAVASCRIPT EVENT HANDLER

Event handlers can be used to manage and verify user input, user actions, and browser actions:

Things that should be done every time a page is loaded
Things that should be done when the page is closed
Action to be performed when a user clicks a button
Content that should be checked when a user enters data

And more…

There are many different methods you can use to allow JavaScript to work with events:

Attributes of the HTML event can directly execute JavaScript code
Attributes of the HTML event can call JavaScript functions
You can assign your own event handling functions to HTML elements
You can prevent the sending or handling of events

And more…

DEEPENING AI

In JavaScript, events represent interactions or changes that occur within the Web page, such as clicking a button, pressing a key, scrolling a page, or loading a file. Events allow developers to create an interactive user interface by responding dynamically to user actions or other external factors.

Detailed description of the main events in JavaScript:

1. Mouse events:

-click: triggers when a user clicks on an element.

-dblclick: triggers when a user double-clicks on an element.

-mouseover: triggers when the mouse hovers over an element.

-mouseout: activates when the mouse exits an element.

-mousemove: activates when the mouse is moved within an element.

-mousedown: activates when a mouse button is pressed over an element.

-mouseup: activates when the mouse button is released on an element.

2. Keyboard events:

-keydown: triggers when a key is pressed.

-keyup: triggers when a key is released.

-keypress: triggers when a key is pressed, but is considered deprecated because it does not handle all types of keys well, such as function keys.

3. Form events:

-submit: triggers when a form is submitted (usually by a submit button).

-change: triggers when the value of an input field, select or textarea changes.

-focus: triggers when an element (such as an input) gets focus.

-blur: triggers when an element loses focus.

4. Window Events (Window Events):

-load: triggers when the page and related resources, such as images and scripts, are fully loaded.

-resize: triggers when the browser window is resized.

-scroll: triggers when the page is scrolled (scrolled).

-unload: activates when a page is closed or the user navigates away from it.

5. Touch events (for touch-screen devices):

-touchstart: triggers when a finger touches the screen.

-touchmove: triggers when a finger is moved on the screen.

-touchend: triggers when a finger is lifted from the touchscreen.

6. Input and selection events:

-input: activates whenever an input value changes.

-select: triggers when some text is selected in a text field or textarea.

7. Custom events:

You can create custom events in JavaScript using the Event or CustomEvent class. These events can be used to handle specific situations in your code, such as a user interface update.

Example:

let eventoPersonalizzato = new CustomEvent(‘mioEvento‘, {
     detail: { messaggio: ‘Questo è un evento personalizzato‘ }
});

// Aggiungi un listener
document.addEventListener(‘mioEvento‘, function(e) {
       console.log(e.detail.messaggio);
});

// Emetti l’evento
document.dispatchEvent(eventoPersonalizzato);

Event Handling

In JavaScript, events can be handled by three main approaches:

1. Assign an event directly in the HTML:

<button onclick=”alert(‘Hai cliccato!’)“>Cliccami</button>

2. Use the event handler property of the element:

const bottone = document.getElementById(‘mioBottone‘);
bottone.onclick = function() {
alert(‘Hai cliccato!‘);
};

3. Use the addEventListener method:

This method allows multiple functions to be associated with a single event and provides more control, such as the option to capture events during propagation.

const bottone = document.getElementById(‘mioBottone‘);
bottone.addEventListener(‘click‘, function() {
     alert(‘Hai cliccato!‘);
});

Event propagation

Events in JavaScript follow a propagation pattern involving three main steps:

1. Capturing Phase: the event is captured by the outermost element and propagated to the target.

2. Target Phase: the event reaches the target element.

3. Bubbling Phase: the event goes up from the target element to higher elements in the DOM hierarchy.

You can prevent an event from bubbling by using event.stopPropagation().

Preventing Default Behavior.

Some events, such as link clicks or form submissions, have default behaviors. To prevent such behaviors, you use event.preventDefault(). Example:

document.getElementById(‘mioLink‘).addEventListener(‘click‘, function(event) {
event.preventDefault();
alert(‘Comportamento predefinito prevenuto!‘);
});

Summary

Events in JavaScript are fundamental to making web applications interactive. Developers can handle a wide range of events to respond to user actions and dynamically manipulate the user interface.

LINKS TO PREVIOUS POST

THE JAVASCRIPT LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB