One of the most popular uses of JavaScript is to add interactivity to web pages. Event handlers are a way to run some JavaScript code when an event occurs. The onclick event handler runs a function when an element is clicked on.
For example, you could have a button that says “Click me!” and when the user clicks on it, an alert pops up saying “Hello!”. Let’s see how this works:
First, we need an HTML element with an onclick attribute:
<button onclick="sayHello()">Click me!</button>
This will create a button that, when clicked on, will run the sayHello function. Next, we need to write the sayHello
function:
function sayHello() { alert("Hello!"); }
Now, when the button is clicked, an alert will appear saying “Hello!”.
You can also add event handlers to other HTML elements, such as links:
<a href="#" onclick="sayHello()">Click me!</a>
This will create a link that, when clicked on, will run the sayHello
function.