Call javascript function from html – Code Example

To call a javascript function from html you need to use events like onclick(), onkeyup(), onmouseover() etc. and pass the javascript function as argument.

Code Example –

1. Calling JS function from html onclick()

<button onclick="runOnClick()">Click Me!!</button>

<script>
  function runOnClick() {
    alert('Button Clicked');
  }
</script>

2. Calling JS function from html onblur()

<input type="text" id="fname" onblur="myFunction()">

<script>
function myFunction() {
  var x = document.getElementById("fname");
  x.value = x.value.toUpperCase();
}
</script>

3. Calling JS function from html onchange()

<input type="text" id="fname" onchange="upperCase()">

<script>
function upperCase() {
  const x = document.getElementById("fname");
  x.value = x.value.toUpperCase();
}
</script>

4. Calling JS function from html onselect()

<input type="text" value="Hello world!" onselect="myFunction()">
<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "You selected some text";
}
</script>

5. Calling JS function from html onsubmit()

<form onsubmit="confirmInput()" action="/code-example-call-javascript-function-from-html">
  Enter your name: <input id="fname" type="text" size="20">
  <input type="submit">
</form>

<script>
function confirmInput() {
  fname = document.forms[0].fname.value;
  alert("Hello " + fname + "!");
}
</script>

6. Calling JS function from html onkeypress()

<input type="text" onkeypress="myFunction()">

<script>
function myFunction() {
  alert("You pressed a key inside the input field");
}
</script>

7. Calling JS function from html onmouseover()

<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>

8. Calling JS function from html onmousedown()

<div onmousedown="WhichButton(event);">
  Click this text (with one of your mouse-buttons)
  <p>
    0 Specifies the left mouse-button<br>
    1 Specifies the middle mouse-button<br>
    2 Specifies the right mouse-button
  </p>

</div>

<script>
function WhichButton(event) {
  alert("You pressed button: " + event.button)
}
</script>

9. Calling JS function from html onload()

<body onload="myFunction()">
  <h2>Hello World!</h2>


  <script>
    function myFunction() {
 
      alert("Page is loaded");
    }
  </script>
</body>

10. Calling JS function from html onerror()

<script>
function imgError() {
  alert('The image could not be loaded.');
}
</script>

<img src="image.gif" onerror="imgError()">