Call a user-defined function onclick event in JavaScript

In this tutorial, I will show you how to call a user-defined function onclick event in JavaScript.

First of all, I need to create an HTML form with a button that users have to click to call the function.

<input type="text" id="name">
<button onclick="greet()">Greet</button>
<div class="greet"></div>

The input tag will take input from the user.

Then I created a button called Greet that needs to be clicked by the user to call the function. onclick="greet()" to target and call the function Greet() on click event that I have defined in the JavaScript code below.

And the div tag where I want to show the output.

Here is the JavaScript code

function greet() {
    let name = document.getElementById('name').value;
    document.getElementsByClassName('greet')[0].innerHTML = `Hey ${name}, Welcome to CodeSpeedy.`;
}

I have defined a function called Greet() that will execute whenever users click the Greet button.

Then, I declared a variable called name to fetch the value of the input. Here’s document.getElementById('name') will target the id of the input tag and the value to get the value of the input that the user enters.

document.getElementsByClassName('greet') will target the class of the div tag. There can be multiple div tags with the same class name. In that case, I can use [0] to target the first div tag where I want to print the output. And ${name}to fetch the value of the name variable.

Output:

Hey samim, Welcome to CodeSpeedy.

 

Leave a Reply

Your email address will not be published. Required fields are marked *