--> Sayadasite: Event Handling

Multiple Ads

Search

Menu Bar

Event Handling

Client side Java script Server side Java script Data types  variables Operators  Expressions  Functions  Objects  Array  Date and math related objects Document objectmodel Event handling

Event handling in JavaScript refers to the mechanism that allows web pages to react to user interactions or browser actions, known as events. 

An HTML event can be something the browser does, or something a user does.

These events can include actions like clicking a button, hovering over an element, submitting a form, or resizing the browser window. 

Here are some examples of HTML events:

An HTML web page has finished loading

An HTML input field was changed

An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

Here's how event handling works in JavaScript:

1. Events:

An event is a signal that something has occurred in the browser or on the web page. Common events include:

Mouse Events: click, dblclick, mouseover, mouseout, mousemove, mousedown, mouseup.

Keyboard Events: keydown, keyup, keypress.

Form Events: submit, change, focus, blur.

Window Events: load, resize, scroll.

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

Example

<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>

Example 2: Alert on Key Press

This example will show how to trigger an alert when a specific key, like the Enter key, is pressed:

// JavaScript code

document.addEventListener('keydown', function(event) {

    if (event.key === 'Enter') {

        alert('Enter key was pressed!');

    }

});

By listening to the keydown event on the entire document, this script checks if the pressed key is the Enter key & displays an alert if true. This can be particularly useful in forms or interactive elements that react to keyboard inputs.

2. Using the ondblclick property (older method):

You can also assign an event handler directly to the ondblclick property of an element.

JavaScript

const myElement = document.getElementById('myButton');

myElement.ondblclick = function() {
  console.log('Element double-clicked!');
};

Example: Mouse Down and Mouse Up Events

The use of the mousedown and mouseup events is exemplified in this scenario: both events apply to a <div> element identified as "mouseUpDownDiv." Two distinct event listeners are established; one responds to the down action of the mouse button, while another reacts upon release or up motion of said button. Upon pressing over the designated div (mousedown), a message indicating that the user has depressed their mouse button appears within your console log. When the user releases the mouse button (mouseup), we also log another message to indicate that the mouse button is up.

<!DOCTYPE html>

<html>

<head>

<title>Mouse Down and Mouse Up Events Example</title>

</head>

<body>

<div id="mouseUpDownDiv" style="width: 600px; height: 100px; background-color: lightblue;"> Please perform mouse down and up event any where in this DIV. </div>

<p id = "output"></p>

<script>

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

const outputDiv = document.getElementById("output"); mouseUpDownDiv.addEventListener('mousedown', function(event) {

outputDiv.innerHTML += 'Mouse button down!' +

JSON.stringify(event) + "<br>";

});

mouseUpDownDiv.addEventListener('mouseup', function(event) {

outputDiv.innerHTML += 'Mouse button up!' +

JSON.stringify(event) + "<br>";

});

</script>

 </body>

</html>

 

2. Event Listeners:

Event listeners are functions that "listen" for specific events on a particular element. When the specified event occurs on that element, the event listener triggers a corresponding function, called an event handler.

The primary method for attaching event listeners is addEventListener().

element.addEventListener('event_type', handler_function);

element: The HTML element you want to listen for events on (e.g., a button, a div).

event_type: The type of event to listen for (e.g., 'click', 'mouseover').

handler_function: The function to execute when the event occurs.

Example:

const myButton = document.getElementById('myButton');
function handleClick() {
  alert('Button clicked!');
}
myButton.addEventListener('click', handleClick);

3. Event Handlers:

An event handler is the function that is executed when an event listener detects the specified event. This function contains the logic that defines how the web page should respond to the event. 

4. Event Object:

When an event handler is called, it often receives an Event object as an argument. This object contains useful information about the event, such as:

event.target: The element that triggered the event.

event.type: The type of event that occurred.

event.preventDefault(): A method to prevent the default action of an event (e.g., preventing a form submission).

event.stopPropagation(): A method to stop the event from bubbling up to parent elements.

Example with Event Object:

const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevents the default form submission
  console.log('Form submitted!');
});

Alternative Methods (less recommended for modern development):

Inline HTML Event Handlers: 

Directly embedding JavaScript code within HTML attributes (e.g., <button onclick="alert('Clicked!')">). This is generally discouraged for larger projects due to separation of concerns and maintainability issues.

DOM Level 0 Handlers: 

Assigning a function directly to an element's event property (e.g., myButton.onclick = handleClick;). This method only allows one handler per event type per element.

By using event handling, developers can create interactive and dynamic web applications that respond effectively to user input and browser actions.

 

 

No comments: