[go: up one dir, main page]

0% found this document useful (0 votes)
16 views44 pages

CN0122 Lect9

Uploaded by

Di
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views44 pages

CN0122 Lect9

Uploaded by

Di
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

JavaScript: Why?

- JavaScript is one of the 3 languages all web developers


must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout(+styling) of web pages
3. JavaScript to program the behavior of web pages

- NOTE: JavaScript and Java are completely different languages, both in


concept and design.
JavaScript: More Details
- Is a dynamic computer programming language
- It is most commonly used as a part of web pages.
- Its implementations allow client-side script to interact with
the user and make dynamic pages
- You might use JavaScript to check if the user has entered
a valid e-mail address or desired length and strength of
password in a form field.
- Usually, JavaScript code is executed when the user
submits the form, and only if all the entries are valid, they
would be submitted to the Web Server.
JavaScript - Advantages
- Less server interaction
- You can validate user input before sending the page off to the server. This saves server
traffic, which means less load on your server.
- Immediate feedback to the visitors
- They don't have to wait for a page reload to see if they have forgotten to enter something.
- E.g. comments in facebook/instagram
- Increased interactivity
- You can create interfaces that react when the user hovers over them with a mouse or
activates them via the keyboard.
- E.g. Suggested friends’ profile in facebook/twitter
JavaScript - Notes
- Whitespace and Line Breaks
- JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
- You can use spaces, tabs, and newlines freely in your program and you are free to format and
indent your programs in a neat and consistent way that makes the code easy to read and
understand
- Semicolons are Optional
- Simple statements in JavaScript are generally followed by a semicolon character
- JavaScript, however, allows you to omit this semicolon if each of your statements are placed
on a separate line
JavaScript - Notes Cont...
- Case Sensitivity
- JavaScript is a case-sensitive language.
- This means that the language keywords, variables, function names, and any other
identifiers must always be typed with a consistent capitalization of letters.
- So the identifiers Time and TIME will convey different meanings in JavaScript.
- NOTE: − Care should be taken while writing variable and function names in JavaScript.
- Comments in JavaScript
- Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
- Any text between the characters /* and */ is treated as a comment.
- This may span multiple lines.
- JS Function: is a block of JavaScript code, that can be executed when "called".
- JS Event: a function can be called when an event occurs, like when the user clicks a button.
JavaScript - Where To

The <script> tag


- In HTML, JavaScript code must be inserted between <script> and </script>
tags.
- Example:

- NOTE:
- Old JavaScript examples may use a type attribute: <script type="text/javascript">.
- The type attribute is not required. JavaScript is the default scripting language in HTML.
JavaScript - Where To
- Most preferred way to include JavaScript in an HTML file are:
1. Script in <head>...</head> section.
2. Script in <body>...</body> section.
3. Script in <body>...</body> and <head>...</head> sections.
4. Script in an external file and then include link in <head>...</head>
section.
1. JavaScript: In <head>...</head> section

- If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head as follows:
2. JavaScript: In <body>...</body> section

- If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document.
- In this case, you would not have any function defined using JavaScript.
- Take a look at the following code.
- Example:
3. JavaScript: In <body> and </head> section

- You can put your JavaScript code in <head> and <body> section altogether as follows:
- Example:
4. JavaScript: In External File

- Useful in cases where you are reusing identical JavaScript code on multiple pages of a site
- The script tag provides a mechanism to allow you to store JavaScript in an external file and then
include it into your HTML files
- This involves the use of the src attribute as seen in the example below:
JavaScript: Variables

- JavaScript variables are containers for storing data values.


- In this example, x, y, and z, are variables:
- NOTE: the use of the var keyword
JavaScript: Identifiers

- All JavaScript variables must be identified with unique names.


- These unique names are called identifiers.
- Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
- The general rules for constructing names for variables (unique identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter
- Names can also begin with $ and _
- Names are case sensitive (y and Y are different variables)
- Reserved words (like JavaScript keywords) cannot be used as names
- NOTE: JavaScript identifiers are case-sensitive.
JavaScript: Arithmetic Operators
- Arithmetic operators perform arithmetic on numbers (literals or variables).

- 5 +1 = 6
- 5-1=4
- 5 * 2 = 10
- 4/2 = 2
- 5%2 = 1
- i =5, i++ = 6
- i =5, i-- = 4
JavaScript: Assignment Operators
- Assignment operators assign values to JavaScript variables.
JavaScript: Adding Strings and Numbers
- The + operator can also be used to add (concatenate) strings.
JavaScript: String Operators
- Adding two numbers, will return the sum, but adding a number and a string
will return a string.
JavaScript: Comparison Operators
- “== ” - equal to
- “!=” - not equal to
JavaScript: Conditions
- Conditional statements are used to perform different actions based on
different conditions.
- Very often when you write code, you want to perform different actions for
different decisions.
- You can use conditional statements in your code to do this.
- In JavaScript we have the following conditional statements:
● Use if to specify a block of code to be executed, if a specified condition is true
● Use else to specify a block of code to be executed, if the same condition is false OR
● Use else if to specify a new condition to test, if the first condition is false
● Use switch to specify many alternative blocks of code to be executed
JavaScript: Conditions ..The if statement

- See Example:
JavaScript: Conditions ..The else statement
- Use the else statement to specify a block of code to be executed if the condition is false.

- See Example:
JavaScript: Conditions ..The else if statement
- Use the else if statement to specify a new condition if the first condition is false.

- See Example:
JavaScript: Statements

- JavaScript statements are "instructions" to be "executed" by the web


browser.
- This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
JavaScript: Programs

- Most JavaScript programs contain many JavaScript statements.


- The statements are executed, one by one, in the same order as they are
written.
JavaScript: Functions

- A JavaScript function is a block of code designed to perform a particular task.


- A JavaScript function is executed when "something" invokes it (calls it).
JavaScript: Functions...syntax
- A JavaScript function is defined with the function keyword, followed by a
name, followed by parentheses ().
- Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
- The parentheses may include parameter names separated by commas:(parameter1,
parameter2, ...)
- The code to be executed, by the function, is placed inside curly brackets: {}
JavaScript: Functions...syntax Cont...
- Function parameters are the names listed in the function definition.
- Function arguments are the real values received by the function when it is
invoked(called).
- Inside the function, the arguments (the parameters) behave as local variables
JavaScript: Functions Invocation
- The code inside the function will execute when "something" invokes (calls)
the function:
● When an event occurs (when a user clicks a button)
● When it is invoked (called) from JavaScript code
● Automatically (self invoked)
JavaScript: Functions...return
- When JavaScript reaches a return statement, the function will stop
executing.
- If the function was invoked from a statement, JavaScript will "return" to
execute the code after the invoking statement.
- Functions often compute a return value. The return value is "returned" back
to the "caller":
JavaScript: Why Functions

- You can reuse code: Define the code once, and use it many times.
- You can use the same code many times with different arguments, to produce
different results.
JavaScript: More on Functions
- The () Operator Invokes the Function
- Using the example above, toCelsius refers to the function object, and toCelsius() refers to the
function result.
- Functions Used as Variable Values
- Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.
JavaScript: Events
- HTML events are "things" that happen to HTML elements.
- When JavaScript is used in HTML pages, JavaScript can "react" on these
events.
- An HTML event can be something the browser does, or something a user
does.
- Examples:
- An HTML web page has finished loading
- An HTML input field was changed
- An HTML button was clicked
- Often, when events happen, you may want to do something.
- JavaScript lets you execute code when events are detected.
JavaScript: Events Cont...
- HTML allows event handler attributes with JavaScript code to be added to
HTML elements.

- Example:
JavaScript: Events Cont...
- JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
JavaScript: Events Cont...
- More Events:
JavaScript: Loops

- Loops can execute a block of code a number of times.


- Loops are handy, if you want to run the same code over and over again, each
time with a different value.
- The for loop is often the tool you will use when you want to create a loop.
- The for loop has the following syntax:
JavaScript: Loops Cont ...

- From the example above, you can read:


- Statement 1 sets a variable before the loop starts (var i = 0).
- Statement 2 defines the condition to be satisfied for the loop to run (i must be less than
5).
- Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
JavaScript: Loops Cont ...
- The while loop
- can execute a block of code as long as a specified condition is true.
JavaScript: Loops Cont ...
- The while loop
- In the following example, the code in the loop will run, over and over again, as long as a
variable (i) is less than 10:
Alert Box
● An alert box is often used if you want to make sure information comes through
to the user.
● When an alert box pops up, the user will have to click "OK" to proceed.

syntax
● window.alert("sometext");
Confirm Box
● A confirm box is often used if you want the user to verify or accept
something.
● When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed.
● If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
Syntax
window.confirm("sometext");
● The window.confirm() method can be written without the window
prefix.
Prompt Box
● A prompt box is often used if you want the user to input a value before
entering a page.
● When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value.
● If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.

Syntax
● window.prompt("sometext","defaultText");
Window Location Href
;

● The window.location.href property returns the URL of the current page.

Example
● Display the href (URL) of the current page:
document.getElementById("demo").innerHTML =
"Page location is " + window.location.href;
END

END

You might also like