JavaScript and HTML

Now that we've reviewed some of the tools for programming JavaScript, let's look at adding code to HTML and running it in a web browser. JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses <link> elements to apply external stylesheets and <style> elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML: the <script> element. Let's learn how this works.

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
Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 License.