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

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

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

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

Note that the function name in the onclick attribute should match the name of the function defined in the JavaScript code. You can also pass parameters to the function by including them in the onclick attribute. For example, if you have a function named showMessage that takes a parameter message, you can call it like this:

html
<button onclick="showMessage('Hello, world!')">Show message</button>

This will call the showMessage function and pass the string "Hello, world!" as the message parameter.

Post a Comment (0)
Previous Post Next Post