Now that you know the basics of JavaScript, you have to actually get it into a webpage. There's a few different ways to do that.
The quick and easy way to get your JavaScript code into an html document is to just include a <script>
tag, and then place the JavaScript code directly inside it. For example:
<html>
<head>
</head>
<body>
This is some cool text in my web page
<script>
var person = "Joe";
alert("Hello, " + person + "!");
</script>
</html>
Any code in a <script>
tag like this will be run as soon as the page loads. In this case, the alert()
function would trigger and show a popup to the user.
As you might imagine, the previous method can become hard to maintain with large or complicated websites. Luckily, there's another way. You can place all your javascript code inside a .js
file, and then just link to it from the <script>
. For example, you would put this code into a myScript.js
file:
var person = "Joe";
alert("Hello, " + person + "!");
Then you can just reference that file from your html document using the src
attribute in the script tag:
<html>
<head>
</head>
<body>
This is some cool text in my web page
<script type="text/javascript" src="myScript.js">
</script>
</html>
This method will produce the exact same result-- as soon as the page loads, the JavaScript code will run and show an alert popup. This method is much cleaner and easier to understand as your files become large.
###DevTools (A Little Bonus!)
In the previous section we used the console.log()
function to write output. If you're wondering where it went, you can take a look at your browser's Developer Tools
. To open the tools in Chrome, you can press Ctrl + Shift + J
on Windows or Cmd + Opt + J
on Mac. Other browsers have developer tools, but Chrome's toolset is much better than the rest. Even if you don't use Chrome for your personal browsing, you may want to use it for development.
These developer tools are insanely powerful when trying to debug an application. If you can think of a feature you might want for debugging, it probably exists here. You can do things like track memory usage, view network traffic, and modify the html and css. If you want to learn more, you can take a this handy write-up from Google.
This has been a fairly surface level introduction to JavaScript, and using it on the web to create simple webpages. We strongly recommend that you check out the "Learn JavaScript" course created by CodeCademy to gain more experience with this language.