When using JavaScript, a lot of times it will be in combination with other languages, like HTML and CSS. JavaScript can be written in three ways. The first way is on a dedicated file linked to from an HTML page. The second way is in script tags on an HTML page. The final way is with events in HTML tags.
JavaScript Files
JavaScript files use the .js extension. It’s best to use this method if you have code that will need to be called from different pages. Putting your JavaScript code in a separate file can also help you remain organized. Keeping JavaScript in its own file can help keep it organized and separate from other languages like CSS and HTML. To call a js file, you would do:
<script src="path/to/your/script.js"></script>
Typically you would call this in your <head>
section or right before your </body>
tag.
Script Tags
The second way to use JavaScript is with script
tags. Like before, we will use script, but instead of using the src
attribute, all of the code will go between the opening and closing tags, like this:
<script>
Code here
</script>
You’d typically use it this way if you don’t have a lot of JavaScript code. It doesn’t always make sense to have a separate js file for one or two lines of code, so this is generally fine to do. These script tags would still typically be used in your <head>
section or right before your </body>
tag.
Inline Events
Sometimes you will want to call JavaScript from an event happening. An event are things like a mouse hovering over a picture or someone clicking on a button. In that case, we would use inline events as part of the HTML tag. For example:
<button onclick="Code here"></button>
This would call the code when someone clicks on the button. In this tutorial you will make a button that pops up an alert.
There you have it, the three ways that you will use JavaScript in web development.