Call a function with onclick() – JavaScript?

Let’s say the following is our button −

<button onclick="displayingMessageOnButtonClick()">Press Me</button>

We need to call a function on the click of above button.


Following is the code −

 Live Demo

<!DOCTYPE html>
<html lang="en">
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
   <p id="showTheTextMessage"></p>
   <button onclick="displayingMessageOnButtonClick()">Press Me</button>
   function displayingMessageOnButtonClick() {
      const showMessage = document.getElementById('showTheTextMessage');
      showMessage.innerHTML = 'Welcome to Javascript Program...'; = 'block';

To run the above program, save the file name anyName.html(index.html). Right click on the file and select the option “Open with live server” in VS Code editor −


The output is as follows −

Now, press the button. Following is the output −

Updated on: 03-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started