JavaScript and HTML
How to Trigger JavaScript from HTML
Within a browser, JavaScript doesn't do anything by itself. You run JavaScript from inside your HTML webpages. To call JavaScript code from within HTML, you need the <script>
element. There are two ways to use script
, depending on whether you're linking to an external script or embedding a script right in your webpage.
Linking an external script
Usually, you'll be writing scripts in their own .js files. If you want to execute a .js script from your webpage, just use <script>
with an src
attribute pointing to the script file, using its URL:
<script src="path/to/my/script.js"></script>
Writing JavaScript within HTML
You may also add JavaScript code between <script>
tags rather than providing an src
attribute.
<script>
window.addEventListener('load', function () {
console.log('This function is executed once the page is fully loaded');
});
</script>
That's convenient when you just need a small bit of JavaScript, but if you keep JavaScript in separate files you'll find it easier to
- focus on your work
- write self-sufficient HTML
- write structured JavaScript applications
Source: Mozilla, https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_JavaScript_within_a_webpage
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.