JavaScript JunkiesJavaScript Junkies Unleash Your Coding Superpowers with JavaScript Junkies

Understand JavaScript Events with Examples

JavaScript events are actions or occurrences that happen on a web page. These can be user actions such as clicking a button, hovering over an element, or typing into a form field, or system actions such as the completion of an image load or the completion of an asynchronous request.

JavaScript events are used to trigger a piece of code to run in response to these actions or occurrences. This code can be used to update the page content, perform validation, or interact with a server.

How Do JavaScript Events Work?

JavaScript events work by listening for a specific action or occurrence to happen on a web page. When that action or occurrence takes place, the event is triggered, and any code associated with that event is executed.

For example, if we want to run a piece of code when a user clicks on a button, we would add an event listener to the button element. The event listener would “listen” for the click event, and when the button is clicked, the associated code would be executed.

Event Listeners and Handlers

In order to handle JavaScript events, we use event listeners and handlers. An event listener is a function that listens for a specific event to occur on an element, and then triggers a corresponding function called an event handler.

For example, if we want to handle a click event on a button, we would create an event listener that listens for the click event, and then triggers an event handler function.

const button = document.querySelector("#myButton");

button.addEventListener("click", handleClick);

function handleClick() {
  // Code to handle click event goes here
}

Types of JavaScript Events

There are many types of JavaScript events, including:

JavaScript onclick events

JavaScript onclick events are a type of event listener that allows you to trigger a function when a user clicks on a particular element in a web page.

<!doctype html>
<html>

<head>
	<script>
		function hiThere() {
			alert('Hi javascriptjunkies!');
		}
	</script>
</head>

<body>
	<button type="button"
			onclick="hiThere()"
			style="margin-left: 50%;">
			Click me event
	</button>
</body>

</html>

JavaScript onkeyup event

The onkeyup event is a type of event listener that is triggered when a user releases a key on their keyboard while focused on a particular element in a web page. This event can be used to execute a function in response to the user’s input.

<!doctype html>
<html>

<head>
	<script>
		var a=0;
		var b=0;
		var c=0;
		function changeBackground() {
			var x=document.getElementById('bg');
			x.style.backgroundColor='rgb('+a+', '+b+', '+c+')';
			a+=100;
			b+=a+50;
			c+=b+70;
			if(a>255) a=a-b;
			if(b>255) b=a;
			if(c>255) c=b;
		}
	</script>
</head>

<body>
	<h4>The input box will change color when UP arrow key is pressed</h4>
	<input id="bg" onkeyup="changeBackground()" placeholder="write something" style="color:#fff">
</body>

</html>

onmouseover event

The onmouseover event is a type of event listener in JavaScript that is triggered when a user’s mouse cursor moves over a particular element on a web page.

<!doctype html>
<html>

<head>
	<script>
		function hov() {
			var e=document.getElementById('hover');
			e.style.display='none';
		}
	</script>
</head>

<body>
	<div id="hover"
		onmouseover="hov()"
		style="background-color:green;
				height:200px;
				width:200px;">
	</div>
</body>

</html>

JavaScript onmouseout event

The onmouseout event is a type of event listener in JavaScript that is triggered when a user’s mouse cursor moves out of a particular element on a web page.

<!doctype html>
<html>

<head>
	<script>
		function out() {
			var e=document.getElementById('hover');
			e.style.display='none';
		}
	</script>
</head>

<body>
	<div id="hover" onmouseout="out()" style="background-color:green;height:200px;width:200px;">
	</div>
</body>

</html>

JavaScript onchange event

The onchange event is a type of event listener in JavaScript that is triggered when the value of an input element, such as a text field, select box, or checkbox, is changed by the user.

<!doctype html>
<html>

<head></head>

<body>
	<input onchange="alert(this.value)"
		type="number"
		style="margin-left: 45%;">
</body>

</html>

JavaScript onload event

The onload event is a type of event listener in JavaScript that is triggered when a web page has finished loading all of its content, including images, scripts, and other resources.

<!doctype html>
<html>

<head></head>

<body>
	<img onload="alert('Image completely loaded')"
		alt="GFG-Logo"
		src=
"https://javascriptjunkies.com/wp-content/cdn-uploads/javascriptjunkies.png">
</body>

</html>

JavaScript onfocus event

The onfocus event is a type of event listener in JavaScript that is triggered when an element, such as a form input field or a link, receives focus, meaning it becomes the active element that can accept user input.

<!doctype html>
<!doctype html>
<html>

<head>
	<script>
		function focused() {
			var e=document.getElementById('inp');
			if(confirm('Got it?')) {
				e.blur();
			}
		}
	</script>
</head>

<body>
	<p style="margin-left: 45%;">
		Take the focus into the input box below:
	</p>
	<input id="inp"
		onfocus="focused()""
		style=" margin-left: 45%;">
</body>

</html>

JavaScript onblur event

The onblur event is a type of event listener in JavaScript that is triggered when an element, such as a form input field or a link, loses focus, meaning it is no longer the active element that can accept user input.

<!doctype html>
<html>

<head></head>

<body style="margin-left: 40%;">
	<p>Write something in the input box and then click elsewhere
		in the document body.</p>
	<input onblur="alert(this.value)">
</body>

</html>

Best Practices for Handling JavaScript Events

When handling JavaScript events, there are several best practices to keep in mind:

  1. Use event delegation to handle events on multiple elements efficiently.
  2. Limit the number of event listeners to improve performance.
  3. Use descriptive event names to improve code readability.
  4. Use event.preventDefault() to prevent default browser behavior.
  5. Always remove event listeners when they are no longer needed to prevent memory leaks.

Common Mistakes to Avoid When Handling JavaScript Events

There are also several common mistakes to avoid when handling JavaScript events:

  1. Attaching too many event listeners can lead to performance issues.
  2. Not using event.preventDefault() can result in unexpected browser behavior.
  3. Using inline event handlers can make code difficult to maintain.
  4. Not removing event listeners can lead to memory leaks and other issues.

Conclusion

JavaScript events are a powerful tool for web developers, allowing them to respond to user actions and system occurrences on a web page. By using event listeners and event handlers, developers can create interactive and dynamic web pages that engage users and provide a better user experience. However, it’s important to follow best practices and avoid common mistakes to ensure that event handling is efficient, effective, and error-free.

Press ESC to close