how to call a function in javascript from html with code example


To call a JavaScript function from an HTML file, you can use the onclick attribute in an HTML element. Here's an example:

html
<!DOCTYPE html> <html> <head> <title>Call a function from HTML</title> <script> function sayHello() { alert('Hello, world!'); } </script> </head> <body> <button onclick="sayHello()">Click me</button> </body> </html>

In this example, we defined a JavaScript function named sayHello that displays an alert message with the text "Hello, world!". We then created a button element and used the onclick attribute to call the sayHello function when the button is clicked.

Note that you need to include the JavaScript code in a <script> tag inside the HTML file, either in the <head> or <body> section. Also, make sure that the function name in the onclick attribute matches the name of the function defined in the JavaScript code.

Post a Comment (0)
Previous Post Next Post