CSCI-1080 Intro To CS: Web Development
Saint Louis University Department of Computer Science
Variables, IF statements and Boolean
List of learning outcomes
By the end of this study session you will be able to:
Define JavaScript variables
Understand the difference between static and dynamic types
Understand the difference between local and global variables
Write simple JavaScript programs that use and change the values of variables
Write if statements to control the flow of a JavaScript program
Use boolean variables in conjunction with if statements
In this section we will create a slide show with dynamic javascripts.
In particular, the logic of our program will need to:
Keep track of which image is currently shown
Each image has a number: we need to count
Define variables and a function to use such variables
Javascript Variables
the keyword var tells javascript we are creating a variable, basically a box (memory location) that can store values.
Then we give a name to that variable. In this programming context, the sign equal is used to assign
a value of zero to the counter variable. Counter becomes equal to zero. So we got a box with a name and a value in it.
Once we have a variable, we can use it in another contex, just as we see down here:
$("counter").text(counter);
Let us analyze the above line of code: we use the name of the variable counter to set (replace)
the text of a particular HTML element to be equal to the value of that counter.
Types and Compilers
Note that in Javascript you don't need to worry about assigning types to variables (e.g., integer or string).
Types are a tool that exists in other programming languages that has certain features,
but comes with some additional complexity. Two examples of variables with static types (in the Java programming language) are:
int a = 1;
string s = “this is a test”;
We say that Javascipt has dynamic types. This roughly means that the compiler (the program that interprets the variables), to translate the human readable code text into a machine readable instruction set, figures out dynamically how much memory needs to be reserved for that variable and where, based on the value assigned to it and on the previous lines of code. For example, an int (integer) in Java only needs 32 bits, but a string needs several bits for each character.
The intuition is that programming languages with static types require programmers to instruct the compiler with more details, specifying exactly how much memory and even where we want to allocate that variables.
Remark: Many people say that Javascipt or other similar languages have “no types”. This is incorrect!
There is always a type; sometimes types are static, e.g., in the C programming language, sometimes they are dynamic, e.g. in Javascript or Python.
Why not all programming languages have the dynamic type feature? It seems easier not having to worry about types. There are many complex reasons for this, but one is speed. Running code only to interpret the types requires time, and sometimes, for example,
in an airplane that quickly needs to make important decisions about balancing the plane based on wind,
this time may not be wasted. In reality, complex computers are not running on planes with heavy memory needs, and this is certainly not an actual problem, but you get the idea. Other examples of programs that cannot waste extra code are small embedded systems,
for example hardware for high-frequency trading, small controllers for human wearable devices like heart-rate monitors, FitBit, etc.
How to use variables in practice
Let us create a simple webpage with only a counter.
Whenever I click on a string number, its value increases.
Before dissecting the code below that does that, see it in action loading this HTML page.
<!DOCTYPE html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js">
</script>
</head>
<body>
<!-- this element will display the variable. It is empty as it will be filled from javascript. -->
<h1 id="number" onclick="count();">
</h1>
<script type="text/javascript">
var counter = 10;
$("#number").text(counter);
function count() {
counter = counter + 1;
$("#number").text(counter);
}
</script>
</body>
</html>
Let us analyze some parts of the code above in details:
As usual, we have the link to the jquery library within the html head tag:
<script src=“http:code.jquery.com/jquery-1.11.3.min.js”>
Then we have an h1 tag with id “number” with a call to the function count():
<h1 id=“number” onclick=“count();”> </h1>
The most important observation is that JavaScript will create the content of the webpage with the function count().
In particular, when we call the jquery:
$(“#number”).text(counter);
The value of the variable counter will replace the HTML named “number”.
The value is initialized to ten with the code line:
Note that another valid example (not used above) of initizing the variable is:
var newCounter = counter +1;
The following line of code gives us the ability to count and “move on”:
that is, increase the value of the current variable counter by one, and overwrite the old value stored into the counter memory location with the new one. We then use the new value of counter to display it in our HTML file.
Local vs Global Variables
Variables declared within a function can only be accessed within the function.
They are local to the function, and so are called local variables.
Consider the example below:
<!doctype html>
<html><body>
<script>
function show_money() {
var money = 2;
alert("In the function, the value is: "+ money);
}
money = 99;
alert("In the main part, the value is: "+ money);
show_money();
alert("In the main part, the value is: "+ money);
</script>
</body></html>
The value of the variable money changes inside the scope of the function show_money(); Even if it has been initialized outside the function to 99, the local value is 2;
Global variables instead are created in the main part and they can work inside or outside functions. For example:
<html><body>
<script>
function show_money() {
alert("In the function, the value is: "+ money);
}
var money = 99;
alert("In the main part, the value is: "+ money);
show_money();
alert("In the main part, the value is: "+ money);
</script>
Note that when local and global variables have the same name, JavaScript gives priority to the local variable inside the function. Note also that if you assign a value to a variable that has not been declared, it will automatically become a global variable. For example:
<!doctype html>
<html><body>
<script>
function show_money() {
money = 2;
alert("In the function, the value is: "+ money);
}
show_money();
alert("In the main part, the value is: "+ money);
</script>
</body></html>
Using Javascript Variables to Create an Image Gallery
We have seen how to change an image dynamically with a click on an element of the HTML page.
Now let us create an image gallery by assigning to each image a number,
and create the code that increases such number, which in turn will translate into an image change on the HTML.
Our variable is the image number.
Create an image layout
Let's create an image layout with the following HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Image Gallery</title>
<!-- import bootstrap, a cool CSS template that does some work for you -->
<link rel="stylesheet"
type="text/css"
href="bootstrap.css"
/>
<!-- import our own stylesheet -->
<link rel="stylesheet"
type="text/css"
href="styles.css"
/>
<!-- import jQuery -->
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div class="container">
<h1>Image Gallery</h1>
<!--
These are the thumbnail images.
with an id to each image which includes the number of that image.
-->
<div class="row">
<div class="col-md-3">
<img id="image1"
class="crop-img" src="img_1.jpg" alt="graffittied building"/>
</div>
<div class="col-md-3">
<img id="image2" class="crop-img" src="img_3.jpg" alt="display of cheese"/>
</div>
<div class="col-md-3">
<img id="image3" class="crop-img" src="img_4.jpg" alt="synethesizer workshop"/>
</div>
<div class="col-md-3">
<img id="image4" class="crop-img" src="img_5.jpg" alt="City night"/>
</div>
</div>
<!--
this is the large image which is
on a row of its own.
-->
<div class="row">
<div class="col-md-1">
<button id="backward"><</button>
</div>
<div class="col-md-10">
<img id="bigImage" class="large-img" src="img_1.jpg" alt="graffittied building"/>
</div>
<div class="col-md-1">
<button id="forward">></button>
</div>
</div>
</div>
</body>
</html>
The images used are here: img_1.jpg img_2.jpg img_3.jpg img_4.jpg img_5.jpg.
The HTML page with the code above is here.
To have it working, please download and unzip the whole package here
Note how we use the following code to number the images:
<img id=“image1”
<img id=“image2”
Note how the image tags have an id, and that id has a number in it.
Add JavaScript to the Body
Let us consider this code:
var counter = 1;
$("#image"+counter).click();
The first line defines the counter variable that keeps track of which image the HTML is currently showing,
while the second line allowes, upon a virtual click, the current image to load into the big image placeholder (large-img).
Virtual click means that the code does exactly what an actual mouse click would do.
The “this” operator
Let us now consider this other piece of JavaScript code:
// when you click on a thumbnail
// it sets the src of the big image
// to be the same as the image
// you clicked on
$(".crop-img").click(function(){
$("#bigImage").attr('src',
$(this).attr('src'));
});
There is a function being called when we click on a selector called crop-img,
and this function, similarly to what we have seen, changes some HTML code.
In particular, the HTML code changed is the src attribute of an HTML images whose selector is called bigImage.
We have seen similar code but here there is something new:
The jquery has a weird variables called this as HTML destination code.
The variable this contains whatever HTML object the web user clicked on. Not really whatever, but only among the objects identified by the CSS selector .crop-img.
The variable this is a placeholder whose value changes dynamcally, just in case there are multiple HTML objects whose ID is crop-img. Having many image HTML objects called crop-img is exactly our goal.
Swap images with variables
Let us see now how I can use this code to swap the image. To do so, consider the following code:
var counter = 1;
$("#image"+counter).click();
The trick is here: note how the input of the jquery is built with a string formed by a text plus the value in the variable counter (which will change dynamically). #image is the start of the ID. When the counter is 2 we will get #image2.
Forward Buttons and Variable Scopes
Let us now consider the following scenario: when we click on the forward button, the image scrolls forward by one.
The javascript code would be:
var counter =1;
$("#forward").click(function (){
counter = counter + 1;
$("#image"+counter).click();
});
Remark: Note that the above piece of code uses a feature unique of Javascript:
We are defining a variable (counter) and then we use this variables inside a function.
This variable is outside the scope of the function!
Using out of scope variables is not allowed in other languages, for example C, Java or Python.
In the case above, the function click captures the scope of that variable.
The operation of capturing the scope of an otherwise out-of-scope variable is called a closure.
Putting it all together
This is the commented javascript code used so far (including a similar code for the backwards button)
<script>
// when you click on a thumbnail
// it sets the src of the big image
// to be the same as the image
// you clicked on
$(".crop-img").click(function(){
$("#bigImage").attr('src',
$(this).attr('src'));
});
// the counter variable that keeps
// track of which image you are showing
var counter = 1;
// virtually click on the current
// image to load it into the big image
$("#image"+counter).click();
// when you click on the backwards
// button select the previous image
$("#backward").click(function (){
// go back one in the counter
counter = counter - 1;
// virtually click on the current
// image to load it into the big image
$("#image"+counter).click();
});
// when you click on the backwards
// button select the next image
$("#forward").click(function (){
// go forward one in the counter
counter = counter + 1;
// virtually click on the current
// image to load it into the big image
$("#image"+counter).click();
});
</script>
You may see it in action here. Click on forward or backward buttons or on the image above and you will see the central image change.
Making Decision (If Statements)
At some point moving forward or backwards in our program above we will run out of images.
When the counter is equal to a value greater than 4, we have to reset the counter to loop over and reshow the first image.
To do so, we introduce an IF statement.
Consider the following code:
if(counter > 4){
counter = 1;
}
$("#image"+counter).click();
If is a built-in word in the language that allows us to make a decision.
The argument of the function if has to be a Boolean expression, that is a value that when executed returns either True or False.
I cannot input anything else rather than a Boolean expression to an If statement. Yes or no, true or false, is it more than 4 or not?
If the boolean expression returns true, then the code inside the body of the if statement is executed.
In this case, just the assignment of the variable counter.
The last code line will then show the first image (#image1).
Local vs Global Variables
Boolean Expressions
|
The name Boolean comes from the English mathematician George Boole.
|
The code written above let users advance an image in the slide show by clicking on a button and if we are at the end, we will go back and start over, looping on the images.
Let us now see how we can advance image automatically. JavaScript has a nice feature that allows us to do that. This below is the special code that does that:
setInterval(function (){
$("#forward").click();
}, 1000);
The function is setInterval, and it has two arguments (separated by a comma). The first argument is a function that reproduces a click on the forward button, while the second argument is 1000, that represents 1000 milliseconds (1 second). So every second the jquery function is called and a click on the forward button is emulated.
Showing a slide show that keeps going on and on may be annoying, or even distracting the user from the rest of the content.
Let us include some JavaScript code that allows the slide show to pause, in this case, when we click on the bigger image.
We are going to implement the different behavior of the slide show with an IF statement.
The decision we are looking at and we need to implement: If we are paused (if pause is true), do nothing, if we are not paused (if pause is false), show me the next image.
We need to tell weather we are paused or not with a Boolean variable, that is, a variable that can only contain true or false.
Consider the following JavaScript code:
var paused = true;
if(!paused){
$("#forward").click();
}
The exlamation point is the equivalent of NOT, and represents the negation (of the Boolean variable in this case).
The last thing I need to worry about is to change (actually assign) the value of the Boolean variable paused when I want to resume the slide show. I resume the slideshow when I click again on the big image.
Look at the following code:
$("bigImage").click(function(){
paused = true;
});
This works right? Well… not really. If I use the code above then I will permantely set the variable paused to true and I will never be able to resume the slide show again.
The correct logic is to assign the Boolean variable paused to its current opposite value. We do that as follows:
$("bigImage").click(function(){
paused = !paused;
});
The not operator will change the value of the variable paused to true if it was false, and to false if it was true.
Putting all together
We can see the complete code with all features discussed so far here below.
The complete code for this example can be downloaded from here.
<script>
// whether the slideshow is paused or not
var paused = false;
// when you click on a thumbnail
// it sets the src of the big image
// to be the same as the image
// you clicked on
$(".crop-img").click(function(){
$("#bigImage").attr('src',
$(this).attr('src'));
});
// the counter variable that keeps
// track of which image you are showing
var counter = 1;
// virtually click on the current
// image to load it into the big image
$("#image"+counter).click();
// when you click on the backwards
// button select the previous image
$("#backward").click(function (){
// go back one in the counter
counter = counter - 1;
// if we are below 1 (the first
// image) loop round to 4 (the
// last image)
if(counter < 1){
counter = 4;
}
// virtually click on the current
// image to load it into the big image
$("#image"+counter).click();
});
// when you click on the backwards
// button select the next image
$("#forward").click(function (){
// go forward one in the counter
counter = counter + 1;
// if we are above 4 (the last
// image) loop round to 1 (the
// first image)
if(counter > 4){
counter = 1;
}
// virtually click on the current
// image to load it into the big image
$("#image"+counter).click();
});
// when you click the big image
// toggle pausing. Set paused to
// not paused, i.e. if it is paused
// set it to not paused, if it is
// not paused set it to paused
$("#bigImage").click(function (){
paused = !paused;
});
// set interval makes it move
// forward every 3 second
setInterval(function (){
// first check if it is paused
if(!paused){
// virtual click the forward
// button
$("#forward").click();
};
}, 3000);
</script>
You can see the final code in action here.
JavaScript Resources
JavaScript is a complex language that would be impossible to teach entirely in a course such as this, but there are many additional resources that you can use to learn more.
This online book is very good:
http://eloquentjavascript.net
The w3schools have good tutorials:
http://www.w3schools.com/js/
as does Mozilla:
https://developer.mozilla.org/en-US/Learn/JavaScript
There are many, many more resources out there and a web search should quickly throw up answers to most questions.
|