In the previous post, we discuss about the HTML event. Now we take a Example of a event inside the HTML file.
Consider we define a small function using JavaScript in script.js which has following code −
function Hello() { alert("Hello, World"); }
Now let's make use of the above external JavaScript file in our following HTML document −
<!DOCTYPE html> <html> <head> <title>Javascript External Script</title> <script src = "/html/script.js" type = "text/javascript"/></script> </head> <body> <input type = "button" onclick = "Hello();" name = "ok" value = "Click Me" /> </body> </html>
Internal Script
You can write your script code directly into your HTML document. Usually we keep script code in header of the document using <script> tag, otherwise there is no restriction and you can put your source code anywhere in the document but inside <script> tag.
Example
<!DOCTYPE html> <html> <head> <title>JavaScript Internal Script</title> <base href = "https://www.tutorialspoint.com/" /> <script type = "text/JavaScript"> function Hello() { alert("Hello, World"); } </script> </head> <body> <input type = "button" onclick = "Hello();" name = "ok" value = "Click Me" /> </body> </html>
For Example
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
<p id="demo"></p>
</body>
</html>
|
---|
Copy this Code and Paste on the Note Pad and Save as a.html (Name would be Different as per the user.).
Output:
After Click on the Button, we got
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
</body>
</html>
|
---|
Output:
After Click on the Button, we got