JavaScript Programs¶
Basic Usage¶
to help you get started, please download this JavaScript starter
web site
the head of the index.html
file looks like this:
<head>
<meta charset="utf-8">
<title>JavaScript Starter Site</title>
<!-- load jQuery -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- load our main JavaScript file (should come after jQuery) -->
<script src="scripts/main.js"></script>
<!-- load CSS styles from styles/mystyle.css -->
<link rel="stylesheet" type="text/css" href="styles/mystyle.css">
</head>
we will add styles and html as needed
JQuery¶
we will be using jQuery to help simplify our JavaScript code
jQuery is a very popular library of JavaScript helper functions that make interacting with the DOM and applying basic special effects much simpler
while you can certainly do JavaScript programming without jQuery, jQuery is so popular and useful that it has practically become a standard part of JavaScript progamming
Example: Hello, world!¶
let’s write a program that simply prints “Hello, word!” on web page as a big title
be sure to download the starter web site
if
you haven’t already done so
we just want some text centered in the middle of the screen
we’ll use this CSS:
/* mystyle.css */
h1 {
text-align: center;
font-family: arial;
font-size: 80pt;
}
in the body of the HTML we’ll put this:
<h1 id="maintitle"></h1>
this is an empty h1
element; we’ll add text to it using JavaScript
it’s id
is maintitle
, and that’s how we will access it in JavaScript
in the scripts
folder we’ve created a file called main.js
containing
this text:
// main.js
$(document).ready(function() {
$('#maintitle').text('Hello, world!');
});
when you load the web page, it should display “Hello, world!” in big letters
Warning
There are a lot of little details to get right here! A wrong name
or a file in the wrong location will almost certainly cause the example not
to work. If you get stuck, here’s a working version of this site
that you can use for reference
.
The Program in Detail¶
let’s go through the contents of our JavaScript code in main.js in detail:
// main.js
$(document).ready(function() {
$('#maintitle').text('Hello, world!');
});
// main.js
is a source code comment, i.e. a note to people reading the code. This is a//
-style comment, i.e. it begins with//
and continues to the end of the line.JavaScript also lets you write comments using
/*
and*/
, e.g. we could have written the comment like this:``/* main.js */``
This style of comment is useful when you want a multi-line source code comment.
Putting the name of the file in a comment at the top is not required, but it is a good practice and a handy way to help keep track of files.
The next line is
$(document).ready(function() {
.The
$
is the standard jQuery way to used to access jQuery functions. Whenever you see$
think “jQuery”.document
is a standard pre-defined JavaScript variable that refers to the entire web page.The jQuery
ready
function ensures that our JavaScript code is not called until the web page is ready, i.e. until the DOM is fully loaded.If you call jQuery on elements before the DOM has loaded into the browser, then you could get (severe!) errors.
All our JavaScript programs will use the jQuery
ready
function. For now, you can just treat this as “boilerplate”, i.e. code that you must always write:// Always call your JavaScript through the following ready function. $(document).ready(function() { // ... code here is called when the page is ready ... });
Next is the line
$('#maintitle').text('Hello, world!');
.It consists of two main parts:
$('#maintitle')
is a jQuery function call that gets a reference to the HTML element whoseid
ismaintitle
. As in CSS, the#
tells jQuery that we are referring to anid
.Next is
.text('Hello, world!')
. This is another jQuery function that sets the text of the element to be'Hello, world!'
.
that’s a lot of explanation for a very simply program!
but all our programs will have the same basic structure
Using Variables in Programs¶
use let
or var
to define variables in JavaScript programs
here is our program:
// main.js
$(document).ready(function() {
$('#maintitle').text('Hello, world!');
});
lets add a variable for the message to be displayed:
$(document).ready(function() {
let message = 'Hello, world!';
$('#maintitle').text(message);
});
the keyword let
indicates we’re defining that message
is a brand new
variable
you could also use var
in place of let
var
is the older, more traditional way to define variables that you will
often see in JavaScript code
you should prefer let
over var
because let
is more strict about
the scope of variables (i.e. where the variables can be used), and can catch
errors that var
misses
Strict Mode¶
we will usually add one more “safety” feature to our JavaScript programs that will help catch errors: strict mode
to do this, we put 'use strict';
at the top of our program, e.g.:
'use strict';
$(document).ready(function() {
let message = 'Hello, world!';
$('#maintitle').text(message);
});
try deleting the let
keyword; viewing the page in Chrome will now cause an
error message to appear in the console saying message
has not been defined
this is good!
you should always use let
to define new variables
let’s add one more variable:
'use strict';
$(document).ready(function() {
let message = 'Hello, world!';
let title = $('#maintitle');
title.text(message);
});
we will often declare variables like this to break out program into smaller steps that are easier to read
Example: Reading from a Text Box¶
lets modify our program to say hello to any name the user enters
to get the name, we’ll use an HTML input
element:
<input type="text" id="username">
then we’ll add a button using an HTML button
element:
<button id="go">Go!</button>
the idea is for the user to enter their name and then click the button to see a personalized message
we’ll use this HTML:
<p>
<input id="username" type="text" placeholder="type your name here">
<button id="go">Go!</button>
</p>
<h1 id="maintitle"></h1>
note the use of the placeholder
attribute: it puts a gray message in the
empty box that disappears when the user starts typing
main.js
contains this code:
'use strict';
$(document).ready(function() {
let goButton = $('#go');
goButton.click(function(event) {
let name = $('#username');
let message = 'Hello ' + name.val() + '!';
let title = $('#maintitle');
title.text(message);
});
});
goButton.click
is a standard jQuery function that lets us specify what
code will be called when an element is clicked with the mouse
a mouse click is called an event, and information about the mouse click is
attached to the variable event
; we don’t need any of that for this
particular program, but other programs might make use of it
inside the call to click
is the function that is called when the go
button is clicked
it does these things:
- assigns the element whose
id
isusername
to the variablename
- it constructs a message to display; recall that
+
adds two strings together; note thatname.val()
is gets the text inside thename
element; if the user clicksgo
without typing anything, thenname
is an empty string (i.e. a string of length 0) - assigns the element whose
id
ismaintitle
to the variabletitle
- sets the text of
title
to bemessage
Notes on Syntax¶
here’s an example of a function call:
$('#go')
$
is the name of the function, and '#go'
is its input
here’s another example:
title.text(message)
this uses dot-notation, and when a function is called like this we call it a
method — it does something to the object title
note that the inputs to the functions are inside round brackets, (
and )
we can also define a function; for example, here is the function passed to the go button from the previous example:
function(event) {
let name = $('#username');
let message = 'Hello ' + name.val() + '!';
let title = $('#maintitle');
title.text(message);
}
this is an example of a function definition
this takes one input named event
(although it happens not to be used
anywhere inside the function)
then the curly braces, {
and }
indicate the function’s body
the body of a function consists of code statements that will be run when the function is called
interestingly, this function has no name; that’s quite common in JavaScript, where we often pass functions as inputs to other functions
e.g. here is how the goButton.click
function from above is called:
goButton.click(someFunction);
the input to a click
function is the function that should be called when
the element is clicked
in JavaScript, it’s common to simply put the function definition directly in the function call as we did above
but you could do it like this if you prefer:
$(document).ready(function() {
let goButton = $('#go');
let clickFunction = function(event) {
let name = $('#username');
let message = 'Hello ' + name.val() + '!';
let title = $('#maintitle');
title.text(message);
}
goButton.click(clickFunction);
});
Text Boxes: Celsius to Fahrenheit¶
lets write a page that will concert a temperature entered in Celsius into Fahrenheit
we’ll use this formula \(F = \frac{9}{5} C + 32\)
and lets agree that the web page will have these elements
- a box where the user enters a temperature in Celsius
- a button the user clicks when they want to convert the temperature to Fahrenheit
- span of text that shows the converted temperature
important: design the page before you write any JavaScript code
the page design tells us all the elements that our JavaScript can refer to
here’s our HTML:
<h1>Celsius to Fahrenheit Converter</h1>
<p>
Celsius: <input id="celsius" type="text">
<button id="convert">Convert</button>
<br><br>
Fahrenheit: <strong><span id="fahrenheit"></span></strong>
</p>
no doubt you could make a nicer-looking page, but this will do for now!
now in main.js
we add this JavaScript:
// main.js
'use strict';
$(document).ready(function() {
let convertButton = $('#convert');
let clickFunction = function(event) {
// get the string the user typed into the text box
let celsiusString = $('#celsius').val();
// convert the Celsius string to a number
let celsiusNum = Number(celsiusString);
// calculate the Fahrenheit value of celsiusNum
let f = (9/5)*celsiusNum + 32;
// get the Fahrenheit element
let fahrenheitDisplay = $('#fahrenheit');
// set the Fahrenheit value as the text of fahrenheitDisplay
fahrenheitDisplay.text(f);
}
// attach the clickFunction to the button
convertButton.click(clickFunction);
});
you should understand both the details of each line, and also the overall structure
the overall structure is this: we add a function to the convert button that will be called when it is clicked; this function reads the Celsius string from the textbox, converts it to Fahrenheit, and then puts that into the Fahrenheit display element
many programs that read data from the user follow this same overall pattern
notice that this program does not check if what the user types into the textbox really is a number!
if you type the word two
into the box and click the button, the result is
NaN
, which means “not a number”
NaN
is the value that JavaScript typically returns when a numeric
calculation has gone wrong
A Checkbox and an if-statement¶
a checkbox is an input element that is either checked or not checked
it often appears as a small square that is either empty, or has a small check- mark in it
lets use a textbox to turn italics on and off for some text
here’s our HTML:
<h1>Setting Styles with Checkboxes</h1>
<input type="checkbox" id="italics">
<label for="italics">Italics</label>
<h1 id="sample" style="text-align: center; font-size: 68pt;">
Sample Text
</h1>
notice we’ve put the CSS style for the h1
element directly in the element
as part of its style
attribute
we did that just for convenience; you can put that in a style file if you prefer
if you run this code now the checkbox will occur, and you can check/uncheck it with the mouse, but it doesn’t do anything
so let’s use JavaScript to connect the checkbox to the sample text so that when we click the checkbox the text is italicized, and when we uncheck it it goes back to normal
here’s some JavaScript code for that:
// main.js
'use strict';
$(document).ready(function() {
let italicsCheckbox = $('#italics');
let sampleText = $('#sample');
let clickFunction = function(event) {
if (italicsCheckbox.prop('checked')) {
sampleText.css('font-style', 'italic');
} else {
sampleText.css('font-style', 'normal');
}
}
// attach the clickFunction to the checkbox
italicsCheckbox.click(clickFunction);
});
we’ve introduced a major new feature of JavaScript: the if-statement
if-statements are used to make decisions, and have this general form:
if (some_boolean_expression_is_true) {
// ... do something ...
} else {
// ... do something else ...
}
only the if-part or the else-part is done — never both!
which part is executed depends upon the value of the boolean expression
in our code above, the boolean expression we are testing is
italicsCheckbox.prop('checked')
; this is how jQuery tests if an HTML
checkbox is checked
this is either true
or false
, i.e. the checkbox is either checked or
not
the statement sampleText.css('font-style', 'italic')
sets the CSS property
of the sampleText element to the value italic
the css
functions is part of jQuery, and is an easy way to set CSS values
using JavaScript
Multiple Checkboxes¶
lets add a few more styles:
<h1>Setting Styles with Checkboxes</h1>
<input type="checkbox" id="italics">
<label>Italics</label>
<br>
<input type="checkbox" id="shadow">
<label>Shadow</label>
<br>
<input type="checkbox" id="underline">
<label>Underline</label>
<h1 id="sample" style="text-align: center; font-size: 68pt;">Sample Text</h1>
now we have 3 textboxes: italics, shadow, and underline
for each one of these 3 textboxes we need to:
- create a function that will be called when the checkbox is clicked
- attach that function to the checkbox using
.click()
this is just a repeat of the same idea 3 times in a row, but using different names and properties each time
// main.js
'use strict';
$(document).ready(function() {
let sampleText = $('#sample');
//
// italics
//
let italicsCheckbox = $('#italics');
let italicsClickFunction = function(event) {
if (italicsCheckbox.prop('checked')) {
sampleText.css('font-style', 'italic');
} else {
sampleText.css('font-style', 'normal');
}
}
// attach the click function to the checkbox
italicsCheckbox.click(italicsClickFunction);
//
// shadow
//
let shadowCheckbox = $('#shadow');
let shadowClickFunction = function(event) {
if (shadowCheckbox.prop('checked')) {
sampleText.css('text-shadow', '3px 3px 5px gray');
} else {
sampleText.css('text-shadow', 'none');
}
}
// attach the click function to the checkbox
shadowCheckbox.click(shadowClickFunction);
//
// underline
//
let underlineCheckbox = $('#underline');
let underlineClickFunction = function(event) {
if (underlineCheckbox.prop('checked')) {
sampleText.css('text-decoration', 'underline');
} else {
sampleText.css('text-decoration', 'none');
}
}
// attach the click function to the checkbox
underlineCheckbox.click(underlineClickFunction);
});
Radio Buttons¶
radio buttons are a basic HTML interaction element that let you pick one thing from a set of choices
only one radio button may be selected at a time
for example, in this HTML we’ve create 4 radio buttons for selecting different kinds of fonts:
<table>
<tr><td><input type="radio" name="font" value="times" checked>Times</td></tr>
<tr><td><input type="radio" name="font" value="verdana">Verdana</td></tr>
<tr><td><input type="radio" name="font" value="georgia">Georgia</td></tr>
<tr><td><input type="radio" name="font" value="courier">Courier</td></tr>
</table>
<h1 id="sample" style="text-align: center; font-size: 68pt;">Sample Text</h1>
notice that each radio button has the same value for the name
attribute
that’s important: the name
of a set of radio buttons must be the same for
each button
the value
attribute of each radio button is what value will be returned by
.val()
when we get its value in JavaScript below
we use a table
to make the layout of buttons look neat and tidy
also notice that the first radio button includes the checked
attribute,
which makes it the default value for all the radio buttons
here’s the JavaScript code that will change the font of the sample text when a radio button is clicked:
// main.js
'use strict';
$(document).ready(function() {
// get a reference to the text element that will change
let sampleText = $('#sample');
// get a reference to "font" radio buttons element
let radioButtons = $('input[name="font"]');
// create the function that will be called when a radio button is clicked
let fontClickFunction = function(event) {
let fontName = $('input[name="font"]:checked').val();
sampleText.css('font-family', fontName);
}
// add the click function to the radioButtons
radioButtons.click(fontClickFunction);
});
look at the line that declares the radioButtons
variable:
let radioButtons = $('input[name="font"]');
$('input[name="font"]')
selects all input
elements with an attribute
called name
with a value of font
, i.e. all the input
elements for
our radio buttons
notice that two kinds of quote-marks are used in $('input[name="font"]')
the first statement of fontClickFunction
gets the value
of the
selected radio button:
let fontName = $('input[name="font"]:checked').val();
the :checked
is important: it causes the checked button to be the one
whose value is returned
Example: Choosing a Pet at Random¶
lets create a page where every time the user clicks a button a picture of a randomly chosen pet appears
here’s the HTML:
<h1>Pet Roulette!</h1>
<p><button id="petbutton">Get Pet!</button></p>
<img id="petpicture">
let’s assume we have these 5 image files for pets: dog.jpeg
, cat.jpeg
,
bird.jpeg
, hamster.jpeg
, and spud.gif
every time petbutton
is clicked, we want to randomly choose and display
one of these image files in the petpicture
element
here’s some JavaScript code that does that:
// main.js
'use strict';
$(document).ready(function() {
// get a reference to the image element where we'll show the picture
let image = $('#petpicture');
// get a reference to the "Get pet" button
let petButton = $('#petbutton');
// create the function that will be called when the button is clicked
let clickFunction = function(event) {
// there are 5 possible pictures, so choose a random number from 1 to 5
let r = Math.floor(5 * Math.random() + 1)
let fileName = "";
let altText = "";
if (r === 1) {
fileName = 'dog.jpeg';
altText = 'a dog';
} else if (r === 2) {
fileName = 'cat.jpeg';
altText = 'a cat';
} else if (r === 3) {
fileName = 'bird.jpg';
altText = 'a bird';
} else if (r == 4) {
fileName = 'hamster.jpeg';
altText = 'a hamster';
} else {
fileName = 'spud.gif';
altText = 'a potato';
}
image.hide();
image.attr('src', 'images/' + fileName);
image.attr('alt', altText);
image.fadeIn('slow'); }
// add the click function to pet button
petButton.click(clickFunction);
});
take a look at clickFunction
; it does a couple of things
first, it chooses a random number from 1 to 5
second, it declares the variables fileName
and altText
third, it uses a big if-else-if structure to set fileName
and altText
depending upon that value of r
finally, it sets the src
and alt
attributes to cause the image (or alt
text) to be displayed
notice that when the src
attribute is set, 'images/'
is added to the
start of fileName
so that the browser will check the correct folder for
the image
image.hide()
and image.fadeIn('slow')
together provide a nice special-
effect for how the image appears on the screen; there are many other similar
sorts of special effects that you can read about on the jQuery website
there are a number of ways this program could be improved/changed, e.g.
- make it work with any number of images, not just 5
- sometimes when you click the button nothing appears to happen because the same image has been chosen; so, modify the button click function so the currently displayed image is not chosen again