CoderDojo Tip: More on JavaScript
 

JavaScript is a powerful and widely-used programming language that runs in web browsers. You can use it to code anything from a simple animation to a fully-fledged video game.

In the book, we added a simple image-swapping script to our web page by embedding it inside the body of the page. If we wanted, though, we could have put the script into a separate file. This is useful if we want the same script to work on multiple pages – it saves us having to add it to each individual page. It also makes pages smaller, so that they load faster.

Cut and paste the JavaScript into an empty plain text file – you just need the bits between the <script> tags, not the tags themselves:

function swapImage() {

var imageDisplayed = document.getElementById('display-image');

if (imageDisplayed.src.match("images/01.png")) {


imageDisplayed.src = "images/02.png";

}

else {

imageDisplayed.src = "images/01.png";

}

}


Save the file using an appropriate name and the .js extension – say, swapper.js

Your .html page now has an empty <script></script> tag in it, where you snipped out the JavaScript. Now you just need to tell the browser that you want to add a script, and where to find it. You do this using the type and src attributes:

<script type="text/javascript" src="swapper.js"> </script>

The type="text/javascript" attribute tells the browser that you are using JavaScript – this will be the same every time. The src="swapper.js" tells it that the script is called swapper.js and is in the same folder as the web page.

If you want to put the .js file somewhere else, you need to put the file path in the attribute. For example, if you made a subfolder called scripts to hold your scripts, the attribute should read src="scripts/swapper.js".

You can find out much more about coding with Javascript online:

Explore Everything
CoderDojo