JS Events

HTML
CSS
C#
SQL

JavaScript Events

In web development, events are interactions or occurrences that happen in the browser, such as a user clicking a button, a page finishing loading, or an element being hovered over. JavaScript allows developers to handle these events through event handlers and listeners.

Event Handling

Event handling involves writing code that responds to specific events. In HTML, you can use event attributes like `onclick`, `onload`, `onmouseover`, etc., to specify JavaScript code that should run when a particular event occurs.

Example:

<!DOCTYPE html>
<html>
 <body>

   <h1 onclick=”this.innerHTML = ‘Ooops!'”>Click on this text!</h1>

 </body>
</html>

In this example, when the user clicks on the `<h1>` element, the `onclick` attribute triggers the specified JavaScript code (`this.innerHTML = ‘Ooops!’`), changing the content of the `<h1>` element.

Event Listeners:

Event listeners are a more modern and flexible way to handle events. They allow you to attach multiple event handlers to a single event on a specific element.

Example:

<!DOCTYPE html>
<html>
<body>
  <button id=”myBtn”>Click Me</button>

<script>

// Defining custom functions
function firstFunction() {
    alert(“The first function executed successfully!”);
}
 
function secondFunction() {
    alert(“The second function executed successfully”);
}

 // Selecting button element
var btn = document.getElementById(“myBtn”);

// Assigning event listeners to the button
btn.addEventListener(“click”, firstFunction);
btn.addEventListener(“click”, secondFunction);

</script>
</body>
</html>

In this example, two functions (`firstFunction` and `secondFunction`) are defined, and both are attached as event listeners to the click event of the button. When the button is clicked, both functions will be executed in the order they were added.

Form Events

Form events are events that occur on HTML form elements, such as input fields, buttons, and the form itself. These events are crucial for building interactive web forms and validating user input.

Here is the list of form events.

Event Type

Explanation

Example HTML Code

Example JavaScript Code

`onfocus`

Occurs when an element gets focus (selected by the user)

input type=”text” onfocus=”console.log(‘Input field has focus!’)”>

document.querySelector(‘input’).addEventListener(‘focus’, function() { console.log(‘Input field has focus!’); });

`onchange`

Occurs when the value of an element changes

<select onchange=”console.log(‘Selected value changed!’)”> <option value=”1″>Option 1</option> <option value=”2″>Option 2</option> </select>

document.querySelector(‘select’).addEventListener(‘change’, function() { console.log(‘Selected value changed!’); });

onselect              

Occurs when the user selects some text in an element

<input type=”text” value=”Select me” onselect=”console.log(‘Text selected!’)”>

document.querySelector(‘input’).addEventListener(‘select’, function() { console.log(‘Text selected!’); });

 

onsubmit

Occurs when a form is submitted

<form onsubmit=”console.log(‘Form submitted!’)”> <input type=”text” name=”username”> <input type=”submit”> </form> 

document.querySelector(‘form’).addEventListener(‘submit’, function(event) { event.preventDefault(); console.log(‘Form submitted!’); });

onreset

Occurs when a form is reset

<form onreset=”console.log(‘Form reset!’)”> <input type=”text” name=”username”> <input type=”reset”> </form>   

document.querySelector(‘form’).addEventListener(‘reset’, function() { console.log(‘Form reset!’); });

Mouse Events

Mouse events are events that occur when the user interacts with the mouse. These events provide a way to capture and respond to various mouse-related actions.

Here is the list of Mouse Events

Event Type

Explanation

Example HTML Code

Example JavaScript Code

onclick

Occurs when an element is clicked

<button onclick=”console.log(‘Button clicked!’)”>Click me</button>

document.querySelector(‘button’).addEventListener(‘click’, function() { console.log(‘Button clicked!’); })

ondblclick

Fires when an element is double-clicked  

<button id=”myButton” ondblclick=”console.log(‘Button double-clicked!’)”>Click me twice</button> 

document.getElementById(“myButton”).ondblclick = function() { console.log(“Button double-clicked!”); };

onmouseover

Fires when the mouse pointer moves over an element

<div id=”myDiv” onmouseover=”console.log(‘Mouse over my div!’)”>Hover over me</div>            

document.getElementById(“myDiv”).onmouseover = function() { console.log(“Mouse over my div!”); };

 

onmouseout              

Fires when the mouse pointer moves out of an element

<div id=”myDiv” onmouseout=”console.log(‘Mouse out of my div!’)”>Hover over me</div>            

document.getElementById(“myDiv”).onmouseout = function() { console.log(“Mouse out of my div!”); };

onmousemove

Fires when the mouse pointer moves within an element              

<div id=”myDiv” onmousemove=”console.log(‘Mouse moving in my div!’)”>Hover over me</div>            

document.getElementById(“myDiv”).onmousemove = function() { console.log(“Mouse moving in my div!”); };

Keyboard Events

Keyboard events in JavaScript allow you to capture and respond to user interactions with the keyboard. These events provide a way to detect when keys are pressed, released, or held down.

Here is the list of Keyboard Events

 Event Type

Explanation

Example HTML Code

Example JavaScript Code

onkeypress              

Fires when a key is pressed down and held

<input type=”text” id=”myInput” onkeypress=”console.log(‘Key pressed: ‘ + event.key)”>

document.getElementById(“myInput”).onkeypress = function(event) { console.log(“Key pressed: ” + event.key); };

onkeydown

Fires when a key is pressed down    

<input type=”text” id=”myInput” onkeydown=”console.log(‘Key down: ‘ + event.key)”>   

document.getElementById(“myInput”).onkeydown = function(event) { console.log(“Key down: ” + event.key); };

onkeyup

Fires when a key is released after being pressed

<input type=”text” id=”myInput” onkeyup=”console.log(‘Key up: ‘ + event.key)”>

document.getElementById(“myInput”).onkeyup = function(event) { console.log(“Key up: ” + event.key); };

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1) Create a basic calculator using a webpage. The webpage should have:
– Two boxes where you can type in numbers.
– Four buttons: one for addition, one for subtraction, one for multiplication, and one for division.
– A space on the page to show the result.

The task is to create a basic calculator using a webpage with two input boxes for numbers, four buttons for addition, subtraction, multiplication, and division, and a space to show the result.

1. Create Input Boxes, Buttons, and Result Area: Use HTML elements (<input>, <button>, <span>) to create two input boxes, four buttons, and an area to display the result.
2. Add Event Listeners: Use JavaScript to add event listeners to the buttons to perform operations when clicked.

Here’s an example program:

<body>

<h2>Basic Calculator</h2>

<label for=”num1″>Number 1:</label>
<input type=”text” id=”num1″>

<label for=”num2″>Number 2:</label>
<input type=”text” id=”num2″>

<br>

<button onclick=”add()”>Addition</button>
<button onclick=”subtract()”>Subtraction</button>
<button onclick=”multiply()”>Multiplication</button>
<button onclick=”divide()”>Division</button>

<br>

<span id=”result”>Result: </span>

<script>
// Function to get the values from input boxes
function getValues() {
var num1 = parseFloat(document.getElementById(“num1”).value);
var num2 = parseFloat(document.getElementById(“num2”).value);
return [num1, num2];
}

// Function to perform addition
function add() {
var [num1, num2] = getValues();
var result = num1 + num2;
displayResult(result);
}

// Function to perform subtraction
function subtract() {
var [num1, num2] = getValues();
var result = num1 – num2;
displayResult(result);
}

// Function to perform multiplication
function multiply() {
var [num1, num2] = getValues();
var result = num1 * num2;
displayResult(result);
}

// Function to perform division
function divide() {
var [num1, num2] = getValues();
// Check for division by zero
if (num2 !== 0) {
var result = num1 / num2;
displayResult(result);
} else {
displayResult(“Cannot divide by zero”);
}
}

// Function to display the result
function displayResult(result) {
document.getElementById(“result”).textContent = “Result: ” + result;
}
</script>

</body>

Output

Addition

Subtraction

Multiplication

Division

2) When you type in two numbers and press one of the operation buttons, it should display the result in the space provided.
A Make a webpage with a button. When you click the button, change the text on the button to say ‘Clicked!’ using the Document Object Model (DOM).

The task is to create a webpage with a button, and when the button is clicked, change its text to ‘Clicked!’ using the Document Object Model (DOM).
– Create Button and Add Event Listener: Use an HTML button element (<button>) and add an event listener to it to change its text when clicked.

Here’s an example program:

<body>

<h2>Change Button Text</h2>

<button id=”myButton”>Click Me!</button>

<script>
// Function to change button text
function changeButtonText() {
var button = document.getElementById(“myButton”);
button.textContent = ‘Clicked!’;
}

// Add event listener to the button
document.getElementById(“myButton”).addEventListener(“click”, changeButtonText);
</script>

</body>

Output

Before Click

After Click

3) Build a form with radio buttons that let users choose a payment method like Credit Card, PayPal, or Bitcoin. When a user picks a method, show a message with their chosen payment method either through a pop-up alert or by updating the content on the webpage.

The task is to create a form with radio buttons for payment methods (Credit Card, PayPal, Bitcoin) and display a message with the chosen payment method either through a pop-up alert or by updating the content on the webpage. 
1. Create Form with Radio Buttons:
Use HTML form elements (<form>, <input type=”radio”>) to create a form with radio buttons for payment methods.
2. Add Event Listener:
Add an event listener to the form to detect when the user selects a payment method.

Here’s an example program:

<body>

<h2>Choose Payment Method</h2>

<form id=”paymentForm”>
<label>
<input type=”radio” name=”payment” value=”creditCard”> Credit Card
</label>
<br>
<label>
<input type=”radio” name=”payment” value=”paypal”> PayPal
</label>
<br>
<label>
<input type=”radio” name=”payment” value=”bitcoin”> Bitcoin
</label>
<br>
<button type=”button” onclick=”showPaymentMethod()”>Submit</button>
</form>

<script>
// Function to show the chosen payment method
function showPaymentMethod() {
// Get the chosen payment method
var selectedMethod = document.querySelector(‘input[name=”payment”]:checked’);

if (selectedMethod) {
// Display the chosen payment method using alert
alert(“Chosen Payment Method: ” + selectedMethod.value);

// Alternatively, update the content on the webpage
// var resultMessage = document.getElementById(“resultMessage”);
// resultMessage.textContent = “Chosen Payment Method: ” + selectedMethod.value;
} else {
// Alert the user to select a payment method
alert(“Please select a payment method.”);
}
}
</script>

</body>

Output

Document

Alert Message

4) Create a countdown timer that decrements every second and displays the remaining time on the webpage. Bonus: Implement a stop button.

The task is to create a countdown timer that decrements every second and displays the remaining time on the webpage. Additionally, a stop button should be implemented to stop the countdown.
1. Create a Countdown Timer and Stop Button:
Use HTML elements (<span>, <button>) to display the remaining time and create a stop button.
2. Implement Countdown Logic:
Use JavaScript to implement the countdown logic that decrements every second.
3. Implement Stop Button Logic:
Add event listeners to the stop button to stop the countdown.

Here’s an example program:

<body>

<h2>Countdown Timer</h2>

<span id=”timer”>10</span> seconds remaining
<br>
<button onclick=”startCountdown()”>Start Countdown</button>
<button onclick=”stopCountdown()”>Stop Countdown</button>

<script>
var countdownInterval;
var remainingTime = 10;

// Function to start the countdown
function startCountdown() {
// Clear any existing intervals
clearInterval(countdownInterval);

// Update the remaining time on the webpage
updateRemainingTime();

// Set an interval to decrement the remaining time every second
countdownInterval = setInterval(function() {
remainingTime–;

// Update the remaining time on the webpage
updateRemainingTime();

// Check if the countdown reaches 0, and stop the countdown
if (remainingTime <= 0) {
stopCountdown();
}
}, 1000);
}

// Function to stop the countdown
function stopCountdown() {
// Clear the interval to stop the countdown
clearInterval(countdownInterval);
remainingTime = 10; // Reset the remaining time
updateRemainingTime(); // Update the remaining time on the webpage
}

// Function to update the remaining time on the webpage
function updateRemainingTime() {
document.getElementById(“timer”).textContent = remainingTime;
}
</script>

</body>

Output

5) Develop a program that utilizes custom events. Create an event listener that responds to a custom event and updates the content on the webpage accordingly.

The task is to create a more flexible and modular program. In this example, we’ll create a custom event and an event listener that responds to the event by updating the content on the webpage.
1. Define Custom Event and Listener:
Use CustomEvent to define a custom event and add an event listener to respond to it.
2. Trigger Custom Event:
Use JavaScript to trigger the custom event when needed.

Here’s an example program:

<body>

<h2 id=”message”>Initial Message</h2>

<button onclick=”triggerCustomEvent()”>Trigger Custom Event</button>

<script>
// Define a custom event
var customEvent = new CustomEvent(‘updateMessage’, {
detail: {
newMessage: ‘Custom Event Triggered!’
}
});

// Add an event listener to respond to the custom event
document.addEventListener(‘updateMessage’, function(event) {
// Access the data from the event detail
var newMessage = event.detail.newMessage;

// Update the content on the webpage
document.getElementById(‘message’).textContent = newMessage;
});

// Function to trigger the custom event
function triggerCustomEvent() {
// Dispatch the custom event
document.dispatchEvent(customEvent);
}
</script>

</body>

Output

Before Click

After Click