Lesson 10

Intro to JavaScript

Using JavaScript to dynamically change our app

Following our 'separation of concerns' idea, rather than typing our JavaScript directly into our content HTML we can instead create a new JavaScript file and link this to our HTML.

1. Create a new JavaScript file

Click the plus in the file panel to the left of Thimble. Thimble will call this new Javascript script-1.js.

Thimble will add a bit of code to this new file, but let's delete that for now to keep things neat.

2. Connect your Javascript to your HTML

Why do we add JavaScript at the bottom of the code?

Unlike CSS, we generally do this from the bottom of the HTML page; this is so browsers can read the HTML and CSS first, which means the app will load faster

3. Test that script.js is connected properly

Now that our JS file is connected, let's do a little test to see if it's working. Add this native 'alert' function code in your app.js file. Then click 'View Your App' and a pop up box should appear.

See *Native Function for more information about the alert function.

What if the alert doesn't show?

If your popup didn't show on the screen, double-check your script.js is connected properly. Also, make sure your browser is not blocking popups.

4. Commenting in JavaScript

Before moving on, add a comment above your alert to remind yourself what the line was for. We do this by adding // at the start of the line. Now we are sure the file is working, we can comment out the alert.

Why do we 'comment out' code?

By commenting out this code rather than deleting it, we ensure that if we have a problem later on down the line we’ll be able to do the same tests as we did originally to try and work out what the error is.

*Native Function

A 'native' function is a function which is already understood by a programming language. For example, all programming languages understand the rules of mathematics. JavaScript has various native functions, for example an 'alert', which produces a pop up.

There are many native functions in JavaScript. Here are some examples:

alert(message), if(condition), prompt(question), Math.round(number), etc

Go to the next lesson

index.html

script-1.js

the web page

New Window
Next Lesson