Event listener

Introduction

Event listener is a function that is called when an event occurs. It is used to listen to events on HTML elements.

Event listener

Using built-in event listener:
<button onclick="myFunction()">Click me</button>
<script>
	function myFunction() {
		alert("Hello World");
	}
</script>
The onclick event occurs when the user clicks on an element.

Using addEventListener:

addEventListener" is a method that is used to add an event listener to an element.
"Click" is the event that is listened to, and the function is called when the element is clicked.
"mouseover" is another event that is listened to, and the function is called when the mouse cursor is over the element.

<div id="txt">Click here</div>
<table border=1>
	<tr>
		<td>1</td><td>2</td><td>3</td>
	</tr>
</table>
<script type="text/javascript">
	document.getElementById("txt").addEventListener("click", function() {
		alert("You clicked on text");
	});
	document.querySelector("table").addEventListener("mouseover", function() {
		alert("You hovered over the table");
	});	
</script>

Task 1

Create a text label and a table cell.
When mouse cursor is inside the table, change text to "Inside".
When mouse cursor is clicked on the text label, display "Outside".

Task 2

Create two buttons, change content of page by pressing the buttons.
       

Task 3

i. Create a textbox. When user enter text, show URL (just append the text. no validation needed)

ii. Show the URL as hyperlink to new tab.

Remark

There are many different ways to add / call an event of an element.

For example, you can use addEventListener method, or you can use onclick attribute.

Reference: Event onclick

Reference

JavaScript Events
HTML DOM EventListener