Introduction to javascript week one
This presentation is the property of its rightful owner.
Sponsored Links
1 / 64

Introduction to JavaScript Week One PowerPoint PPT Presentation


  • 92 Views
  • Uploaded on
  • Presentation posted in: General

Introduction to JavaScript Week One. Day One. Official stuff Syllabus Grades Website Class Procedures Setting up your work environment Development Tools Debugging Tool Jump into Code!. 1. Tools for Class. Dreamweaver Already installed on campus PCs

Download Presentation

Introduction to JavaScript Week One

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Introduction to javascript week one

Introduction to JavaScriptWeek One


Day one

Day One

  • Official stuff

    • Syllabus

    • Grades

    • Website

    • Class Procedures

  • Setting up your work environment

    • Development Tools

    • Debugging Tool

  • Jump into Code!


1 tools for class

1. Tools for Class

  • Dreamweaver

    • Already installed on campus PCs

    • It is the IDE of choice for other classes in the Web program

    • While your projects are not required to be hosted on a remote server, it is a good idea because then you will have a backup copy that you can easily access from other machines.

    • Please TAKE NOTES on how we set this up in class, so that we will not have to go over this multiple times.


I am new to dreamweaver too

I am new to Dreamweaver, too.

  • I have used many other IDEs, but this is my first time using Dreamweaver. If you have used this tool in the past, please extend your help to others as we work through the setup.

  • You will need your username and password and absolute path to your public_html directory from either Zephir or Edison. You are welcome to use your own server, but at your own risk, as I will not be able to help you debug your connection.


Other tools for class

Other tools for class

  • Please install Firebug as an extension to Firefox. (There is a link on the class webpage.)

  • Please do NOT use IE for developing your homework, as there may be some incompatibilities.

  • And read chapters 1 and 15, as you will find tutorials for debugging your code.


Concepts about javascript

Concepts about JavaScript


Server side vs client side

JavaScript runs in your BROWSER. It is a CLIENT-SIDE scripting language.

PHP is a scripting language that runs on a SERVER. The output of its execution is then sent to your browser for display.

Both are SCRIPTING languages. This means that they are INTERPRETED and do not need to be compiled.

Server-side vs Client-side


Java interpreters are built into browsers

Java interpreters are built into Browsers

  • Because of this, you may find difference in behavior between browsers. Please use FIREFOX in class.

  • If you develop for clients, then become familiar with Quirksmode, which is linked to the class website.


What javascript can do

What JavaScript Can Do


What javascript can not do

What JavaScript Can NOT do


Why use javascript

Why use JavaScript?

To make your web application fast and responsive, without requiring the delays of a round trip to the server to process user interactions.


2 writing your first script

2. Writing your first script


Introduction to javascript week one

HTML

  • Hyper Text Markup Language

  • A set of tags used to define how elements (text, links, pictures…) will be displayed in a web page

<html>

<body>

Text that appears in my webpage!

</body>

</html>


Html javascript

HTML + JavaScript

<html>

<body>

<script type=“text/javascript”>

document.write(‘Hello World’);

</script>

</body>

</html>


How to add js

HOW to add JS

<script type=“text/javascript”>

// content

</script>

This line says we are now going to be using a scripting language to modify our html page, and we choose JavaScript. As JavaScript has become the default script language in browsers, the type tag is not typically needed anymore.

HTML5 does not require the type.

HTML4.01 and XHTML1.0 does not require the type, but it will not validate properly.


Where to add js

WHERE to add JS

  • In the HEAD section of the document

  • At the bottom of the document

  • Inline, anywhere

  • Linked as an external file

    • We will see an example with Jquery

    • It goes in the head before any other JS code

    • Do NOT submit your homework this way, because I will not have source code to correct

  • In a “document onload” function in the head

    • By week two, this is how we will add all our code

However, as we shall see, JS is interpreted as the page loads, so the location determines when the JS will run and what it knows. We will see this more in a demo.


Comments

Comments

  • Comments are used to explain what your code does

  • The ‘//’ tells javaScript to ignore the line of text

//The line below will write hello world

document.write(‘<p>Hello World</p><br/>’);


Comments cont

Comments (cont…)

You can use the ‘//’ to make comments on the end of lines

document.write(“hi”); //a comment


Comments cont1

Comments (cont…)

We can also make multi-line comments with the symbols /* and */

/*All3 lines will be ignored

ignoring this

and this

*/

document.write(‘<p>Hello World</p><br/>’);


Comments cont2

Comments (cont…)

You can use comments to ignore code for debugging…

/*

Commenting this out because its causing an error

document.write(‘<p>Hello World</p><br/>’);

*/


Statements

Statements

  • A statement is an executable line of code. It is terminated by a semi-comma (;) which tells the interpreter to execute the line before continuing on to the next one.

    <script>

    alert(“Hello world”);

    </script>


Statements across multiple lines

Statements across multiple lines

You won’t use this too often. It is mostly to make code easier to read in an IDE without scrolling to the right.


Communication popups

Communication Popups

  • Alert

    • Informs the user, then is dismissed

  • Prompt

    • Requests text input from the user

    • Can be given a default value

    • Can be cancelled

  • Confirm

    • Requests yes/no from the user

Alert is GREAT for debugging.


Writing directly to the document

Writing directly to the document

  • document.write(“TEXT”);

  • This is a JavaScript command for writing text to a webpage.

  • We will use it for the first few weeks, and you can use it for homework 1 and 2. But after that, we will use another method and be marked down for using it.


Using the onload function

Using the “onload” function

<script>

window.onload = function() {

someCode;

}

</script>

We will come back to this next week….


3 debugging tricks

3. Debugging Tricks

  • Alert

  • Console.log

  • Breakpoints

  • Commenting out code


Kinds of errors

Kinds of errors

  • Syntax – the interpreter will get confused and simply quit (similar to a compiler error)

  • Runtime – not all paths have been tested and the user may choose a path leading to a variable not being defined, for example

  • Logic – everything runs fine from a JS point of view, but you get the wrong answer


Top mistakes that require debugging

Top Mistakes that Require Debugging

  • Unmatched parenthesis, brackets, or quotes

  • Using curly/smart quotes instead of singles or doubles

  • <XXXXX> is not defined (function or variable)

  • Missing “;”

  • Using a reserved word

  • Case sensitivity

  • Incorrect path to resource (file or URL)

  • Using “=“ instead of “==“


How to not spend so much time debugging

How to not spend so much time debugging

  • This is VERY important – write your code in SMALL increments – consider adding ONE line of code at a time. Test. Then add another.

  • If you write big multi-line chunks of code and get stuck, then the first thing I will have you do is comment out all your code, and then we will add each line of code back one line at a time. So, get in the habit of writing it this way to begin with!


4 data variables operators

4. Data, Variables, Operators


Data literals

Data (Literals)

  • Numbers

    • Integers, Decimals, Sci Notation

  • Strings

    • Quotes are required

  • Booleans

    • Keywords true and false (no quotes)

  • NULL

    • Absence of data


Variables

Variables

  • Hold data to be used at a later time

  • If you have not declared a variable it will be automatically declared when you use it. But this will change the scope so use var (we will learn more when we get to functions).

  • You can reassign values, but if you redeclare using var, you may get an error.

  • You can declare and initialize, or just declare and initialize later

    ex. varx = 6;

    vary;

    y = 7;


Rules for naming variables

Rules for naming variables

  • Avoid keywords

  • Names must begin with $, _ or a letter

  • Names can only contain $, _, numbers and letters

  • Names are case sensitive


Loosely typed languages

Loosely Typed Languages

  • Languages that don’t care about the variable types. You can start off using a variable as one type and switch to another. JavaScript is an example of this.

  • So, for example, you don’t need to specify whether you are working with a string or a number, or whether a number is an integer or a float, etc.


Arithmetic operators

Arithmetic Operators


Assignment operators

Assignment Operators


Operator examples

Operator Examples

var total= 10;

total *= 10; // total is now 100

total -= 32; // total is now 68

total += 2; // total is now 70

total /= 2; // total is now 35

total %= 3; // total is now 2


Order of operations

Order of Operations

Follows PEDMAS rules

Parentheses, Exponentials, Division/Multiplication, Additional/Subtraction

“Please excuse my dear aunt sally”

var answer = 4 + 6 * 5 //is 34

var answer = (4 + 6) * 5 //is 50


Working with strings

Working with Strings

  • Use var keyword and then place either single or double quotes around the literal data.

  • If you need a quote inside a string, you have two choices:

    • 1) Use the OTHER kind of quote inside

    • 2) Use the escape character

varx = “Hello Deer”;

vary = ‘The Dog said “Hello” to the Deer.’

Varz = “The Dog said \”Hello\” to the Deer.”


Strings concatenation operator

Strings Concatenation Operator

  • We can add two strings together using the ‘+’ sign

  • To add spaces between the strings:

var greeting = “hi”;

var phrase = “how are you”;

var sentence = greeting + phase;

var sentence = greeting + ‘ ‘ + phase;


Mixing strings and numbers

Mixing Strings and Numbers

The default behavior is to convert the number to a string:

A string can be converted to a number by appending a “+” (NO SPACE) or by using the built-in Number function

var a = 5;

var b = “7”;

varc = a + b; //”5 + 7”

vard = a + +b; //12

vare = Number(b) + a; // 12


5 conditionals

5. Conditionals


Comparison operators

Comparison Operators


If statement

If statement

If(condition) {

conditional code

}

Note: You should indent the code inside the curly brackets. We call the content inside the curly bracket a “block”.


If example

If example

var age = 17;

If(age < 21) {

alert(“you should not be drinking”);

}


If else statement

If…else statement

  • else is the coding term for otherwise.

    If(condition) {

    code we run if condition is true

    } else {

    code we run if condition is false

    }


If else example

If…else example

var age = 27;

If(age < 2) {

alert(“you’re just a baby”);

} else {

alert(“time to grow up!”);

}


If else if else statement

If…else if…else Statement

If(condition1) {

code we run if condition is true

} else if(condition 2) {

code we run if condition1 is false and condition2 is true

} else {

code we run if both condition1 & condition2 are false

}


If else if else statement1

If…else if…else Statement

var age 27;

If(age < 2) {

alert(“you’re just a baby”);

} else if(age < 11) {

alert(“you’re not even a teen yet”);

} else if(age < 20) {

alert(“teens equal trouble”);

} else {

alert(“just man up already”);

}


Nested if statements

Nested if statements

If(condition) {

if (some other condition) {

// do something else

}

} else {

code we run if condition is false

}

You can combine and nest them


Multiple conditions

Multiple Conditions

var a = 7;

var b = 10;

// if a Is greater than 8 or b is less than 12

If(a > 8 || b < 12) {

alert(‘hello’); //this will alert

}


Logical operators

Logical Operators


Problems with numeric tests

Problems with numeric tests

var grade = 95;

If (grade > 60) {

// good but keep trying

} else if (grade > 80) {

// you really understand this stuff

} else {

// congrats! Doing great!

}

The code will branch to the FIRST condition that is true.

Also – what happens if grade is 50???


A better way bounds

A better way: bounds

var grade = 95;

If (grade > 60 && grade <= 80) {

// good but keep trying

} else if (grade > 80 && grade <= 90) {

// you really understand this stuff

} else if (grade > 90) {

// congrats! Doing great!

} else {

// maybe you should consider dropping

}

I do a lot of numerical work so this is a pet peeve of mine.

Please use upper and lower bounds on numerical conditionals in your homework for full credit!!!


Switch case syntax

Switch Case Syntax

The syntax for the switch statement is:

Switch (expression) {

case label:

statement(s);

break;

case label:

statement(s);

break;

...

default:

statement(s);

}


Case line

Case line

  • We test the expression against the label.

  • We can have multiple lines to execute after the case.

    switch(expression) {

    case label:


Switch case syntax1

Switch Case Syntax

var today = "Wednesday";

switch (today) {

case "Monday":

alert("Today is Monday“);

break;

case "Tuesday":

alert("Today is Tuesday“);

break;

...

default:

alert("Invalid day!);

}


Break

Break

  • Notice the break:

    case "Monday":

    alert("Today is Monday“);

    break;

  • If we don’t include this we will execute every statement after every case line following a true case.


No break

No Break

If we have no break we will execute every line following a true condition

var test = 5;

switch(test) {

case 5:

document.write(“Equals 5");

case 4:

document.write(“Equals 4");

default:

document.write("didn’t satisfy");

}

Output: Equals 5Equals 4didn’t satisfy


Multiple lines in switch case

Multiple Lines in Switch Case

switch(dayOfWeek) {

case “Monday”:

dayOfWeek = “Tuesday”;

document.write(“Mondays are great<br/>”);

document.write(“It’ll be Tuesday soon”);

break;

}

We can add as many lines for each case as we like


A few validation tricks for the first home work

A few validation tricks for the first home work…

  • Checking if the field is empty

    trim()

    null or empty string

  • Checking if the field contains a number

    charAt()

    substring()

    parseFloat()

  • Displaying a number with a fixed number of decimal places

    toFixed()


Validating prompt data

Validating Prompt Data

// ask the user for their name using prompt

varx = prompt("Please enter your name");

// this will remove both leading and trailing white space

x= x.trim();

// cross-browser check for whether they entered anything

if (x != null && x != "") {

varwm = "<h1>" + "Welcome " + x + "</h1>";

document.write(wm);

} else {

// handle no data with a message (for now)

document.write("Hey! You have to put something in the field!");

}


Converting prompt data to numbers

Converting Prompt Data to Numbers

varprice = prompt("How much did you pay for your book?");

// declare a variable for converting to a number, if string was entered

varnumericprice;

// if the first char is a "$", then lop and turn into a number (float)

if (price.charAt(0) == "$") {

price = price.substring(1);

numericprice= parseFloat(price);

} else {

// price is already a number, so assign

numericprice= price;

}

// compute price plus WA State sales tax

numericprice*= 1.085;


Displaying numbers with fixed digits

Displaying Numbers with Fixed Digits

document.write("You paid how much? " + "$" + numericprice.toFixed(2) + "!?!<BR><BR>");


  • Login