call a function javascript how to call a function in javascript from html file

 To call a JavaScript function defined in a separate JavaScript file from an HTML file, you need to include the JavaScript file in the HTML file using the <script> tag. Here's an example:

index.html:

html
<!DOCTYPE html> <html> <head> <title>Call a function from JavaScript file</title> <script src="script.js"></script> </head> <body> <button onclick="greet()">Say hello</button> </body> </html>

script.js:

javascript
function greet() { alert('Hello, world!'); }

In this example, we have an HTML file named index.html that includes a JavaScript file named script.js using the <script> tag in the <head> section. The JavaScript file defines a function named greet that displays an alert message with the text "Hello, world!". The HTML file also contains a button element that calls the greet function using the onclick attribute.

Note that the JavaScript file should be included before any code that uses the functions defined in it. Also, make sure that the path to the JavaScript file in the src attribute of the <script> tag is correct.

Post a Comment (0)
Previous Post Next Post