Intro to JavaScript
Goals
- High-level Computer architecture
- Experience JS at work
- Practice using variables
- Practice using some JavaScript built-in methods:
- User input with
prompt()
- User output with
alert()
- User input with
- Perform calculations using JS
Tip: As you work, be sure to keep Chrome's Javascript Console open to check for errors. You can get the console by
- clicking
command
+option
+j
or from - Chrome --> View --> Developer --> Javascript Console
Task 0:
Pay attention to the new button tag in the HTML code. Clicking on a button is an event of interest. The onClick event handler is defined to specify the reaction to that event.
Can you figure out how to change the event handler so that when the user clicks on the button the background of the web page changes to -let's say- red?
Javascript is used to create dynamic (what does δυναμη mean?) web pages: The content or the style of a page can change at moments of our choice!
JavaScript: Where to?
Take a look at the following pages and try to answer the question:
"Where does Javascript code when working with an HTML document?"
-
or there
- but also even better over there
Inside a Computer
The most basic computer components: CPU, main Memory and Secondary memory.
Variables live in the main memory. A variable holds one and only one value at any given time. But that value can change over time.
Task 1: Evaluating expressions
Here is a sequence of JavaScript statements:
let x = prompt("Give me a number.");
let y;
x = x - 2;
y = x;
alert("The value of x is " + x);
x = 2 * x;
alert("The new value of x is now " + x);
x = x + 1;
alert("x is now " + x);
y = x;
alert("y divided by 3 is: " + y/3);
Hand-execute this piece of code. Make a note of the results you expect. Also, use the javascript console to enter statements and verify your prediction.
Task 2: Input and output
Create a new HTML document named ask_name.html
.
Add some HTML code in there. Anything you want!
Then, add JavaScript statements to do the following:
- Prompt the user for their first name
- Save this information in a variable
- Use the built-in
alert()
method to show a pop up window with a personalized greeting
For instance, if the user enters the name "Kayla", the message could say:
Hi, Kayla! It is very nice to meet you.