OneBite.Dev - Coding blog in a bite size

call a javascript function in html

Code snippet for how to how to call a javascript function in html with sample and detail explanation

In web development, integrating JavaScript and HTML plays a crucial role in enhancing the browser-based user experience. This article will provide a clear and straightforward guide on how to call a JavaScript function from within HTML.

Code snippet

Here’s a simple example. Suppose we have a JavaScript function called sayHello() and we want to call it when a button is clicked in the HTML.

<!DOCTYPE html>
<html>
<body>

<button onclick="sayHello()">Click me</button>

<script>
function sayHello() {
  alert("Hello, World!");
}
</script>

</body>
</html>

Code Explanation

The code above demonstrates how a JavaScript function can be called in HTML. Here’s a step-by-step walkthrough of what is happening:

  1. A button is created in HTML with the code <button onclick="sayHello()">Click me</button>. This button, when clicked, will trigger the sayHello() function declared in JavaScript.

  2. The onclick attribute is an event attribute that can be added to HTML elements to define what JavaScript code to run when the element is clicked.

  3. Below the button code, we have a script tag, <script></script>, which encloses our JavaScript code.

  4. Inside the script tags, the function sayHello() is declared. This function, when called, will execute the contained code, which in this case is alert("Hello, World!");.

  5. The alert function is part of JavaScript and is used to pop up a little notification window in the browser. In this case, it will display the message “Hello, World!“.

  6. Now, because of the onclick attribute in the button tag, every time the button is clicked, the sayHello() function is called and “Hello, World!” will be displayed.

Remember, JavaScript is case-sensitive, so ensure that the function name you’re calling matches exactly with the declared function name. Give this a try in your own code and see the results for yourself. Happy coding!

javascript