Webprog-js
Webprog-js
2
What can JavaScript do?
<button type="button"
onclick='document.getElementById(
"demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>
</body>
</html>
3
Change attribute value
<p>In this case JavaScript changes the value of the src (source) attribute of an
image.</p>
<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn
on the light</button>
<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn
off the light</button>
</body>
</html>
4
5
JavaScript can change the style of an
HTML element
<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p id="demo">JavaScript can change the style of an HTML
element.</p>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'
">Click Me!</button>
</body>
</html>
6
JavaScript can hide/Show HTML
elements.
<!DOCTYPE html>
<html>
<body>
<p id="demo">JavaScript can hide HTML elements.</p>
<button type="button"
onclick="document.getElementById('demo').style.display='none'">
Hide</button> <br/>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">
Show</button>
</body>
</html>
7
Where to Insert JavaScript
8
JavaScript Functions and Events
9
JavaScript in <head>
<!DOCTYPE html>
<html>
In this example, a
<head>
JavaScript function
<script>
is placed in the
<head> section of function myFunction() {
an HTML page. The document.getElementById("demo").innerHTML =
"Paragraph changed.";
function is invoked
(called) when a }
button is clicked: </script>
</head>
<body>
<h2>Demo JavaScript in Head</h2>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try
it</button>
10 </body>
</html>
JS Insertion
JavaScript in <body>
a JavaScript function can be place in the <body>
section of an HTML page.
External JavaScript
Scripts can also be placed in external files:
External file: myScript.js
function myFunction() {
document.getElementById("demo").innerHTML =
"Paragraph changed.";
}
11
JS Insertion
12
External JavaScript Advantages
13
External JavaScript Advantages
External References
An external script can be referenced in 3 different
ways:
14
JavaScript Output
15
Using innerHTML
16
JavaScript Print
You can call the window.print() method in the browser
to print the content of the current window.
<!DOCTYPE html>
<html>
<body>
<h2>The window.print() Method</h2>
<p>Click the button to print the current page.</p>
<button onclick="window.print()">Print this
page</button>
</body>
</html>
17
JavaScript Statements
18
JavaScript Statements
Examples
let a, b, c; // Declare 3 variables
a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c
JavaScript Line Length and Line Breaks
For best readability, programmers often like to avoid
code lines longer than 80 characters. If a JavaScript
statement does not fit on one line, the best place to
break it is after an operator.
19
JavaScript Code Blocks
20
JavaScript Code Blocks
JavaScript Keywords
JavaScript statements often start with a keyword to
identify the JavaScript action to be performed. (var, let,
const, if, switch, for, function , return)
https://www.w3schools.com/js/js_reserved.asp
21
JavaScript Syntax
22
JavaScript Syntax
JavaScript Literals
The two most important syntax rules for fixed values are:
1. Numbers are written with or without decimals:
10.50
1001
2. Strings are text, written within double or single
quotes:
"John paul"
'John paul'
23
JavaScript Syntax
JavaScript Operators
JavaScript uses arithmetic operators ( + - * / ) to compute values:
(5 + 6) * 10
JavaScript uses an assignment operator ( = ) to assign values to variables:
let x, y;
x= 5; y = 6;
JavaScript Expressions
An expression is a combination of values, variables, and operators, which computes
to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50
Expressions can also contain variable values: x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
24
JavaScript Syntax
JavaScript Comments
Code after double slashes // or between /* and */ is treated as a comment. Comments are ignored, and will
not be executed:
let x = 5; // I will be executed
// x = 6; I will NOT be executed
JavaScript Identifiers / Names
Identifiers are JavaScript names. Identifiers are used to name variables and keywords, and functions. The
rules for legal names are the same in most programming languages.
A JavaScript name must begin with:
A letter (A-Z or a-z)
A dollar sign ($)
Or an underscore (_)
Subsequent characters may be letters, digits, underscores, or dollar signs.
Note
Numbers are not allowed as the first character in names.
This way JavaScript can easily distinguish identifiers from numbers.
JavaScript is Case Sensitive
All JavaScript identifiers are case sensitive.
The variables lastName and lastname, are two different variables.
25
JavaScript Syntax
Note : The let keyword was introduced in ES6 (2015). Variables
defined with let cannot be Redeclared. But possible for var.
Variables defined with let must be Declared before use.
When to Use JavaScript var?
The var keyword is used in all JavaScript code from 1995 to 2015.
If you want your code to run in older browser, you must use var.
26
JavaScript Assignment Operators
Assignment operators assign values to JavaScript
variables.
27
JavaScript Comparison, logical and type
Operators
JavaScript Logical Operators
28
JavaScript Data Types
JavaScript variables can hold different data types: numbers,
strings, objects and more:
let length = 16; // Number
let lastName = "Johnson"; // String
let x = {firstName:"John", lastName:"Doe"}; // Object
Extra large or extra small numbers can be written with
scientific (exponential) notation:
Example
let y = 123e5; // 12300000
let z = 123e-5; // 0.00123
You can use quotes inside a string, as long as they don't match
the quotes surrounding the string. Using ¨¨.
29
JavaScript Data Types
JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5; let y = 5; let z = 6;
(x == y) // Returns true
(x == z) // Returns false
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
30
JavaScript Data Types
JavaScript Booleans
Booleans can only have two values: true or false.
Example
let x = 5; let y = 5; let z = 6;
(x == y) // Returns true
(x == z) // Returns false
typeof "" // Returns "string"
typeof "John" // Returns "string"
typeof 0 // Returns "number"
typeof 314 // Returns "number"
typeof 3.14 // Returns "number"
typeof (3) // Returns "number"
typeof (3 + 4) // Returns "number"
31
JavaScript Data Types
Undefined
In JavaScript, a variable without a value, has the value
undefined. The type is also undefined.
Example
let car; // Value is undefined, type is undefined
Empty Values
An empty value has nothing to do with undefined.
An empty string has both a legal value and a type.
Example
let car = ""; // The value is "", the typeof is "string"
32
JavaScript Data Types
JavaScript Arrays
JavaScript arrays are written with square brackets. Array items are separated by commas.
The following code declares (creates) an array called cars, containing three items (car
names):
Example
const cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so on.
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name:value pairs, separated by commas.
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age, and
eyeColor.
You can access object properties in two ways:
objectName.propertyName or objectName["propertyName"]
33
JavaScript Data Types
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects. Methods are stored in
properties as function definitions.
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object. I.E. this.firstName means the
firstName property of this. I.E. this.firstName means the firstName property of person.
34
JavaScript Data Types
What is this?
35
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 Function 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: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function 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)
36
HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events: 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.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. With
single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to a <button> element:
Example 1
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?
</button>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of its own element (using this.innerHTML):
Example 2
<button onclick="this.innerHTML = Date()">The time is?</button>
37
Common HTML Events
Here is a list of some common HTML events:
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an
HTML element
onmouseout The user moves the mouse away from
an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
38
JavaScript if else and else if
Very often when you write code, you want to perform different actions for
different decisions.
39
JavaScript if else and else if
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
40
JavaScript switch
switch (new Date().getDay()) {
case 0:
switch(expression) {
break;
case 1:
break;
// code block case 2:
break;
case y: case 3:
break;
break; case 4:
break;
} day = "Friday";
break;
case 6:
41 day = "Saturday";
}
JavaScript switch
} <script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];
before the execution of the code block. for (i = 0, len = cars.length, text = ""; i < len; i+
+) {
text += cars[i] + "<br>";
42
JavaScript switch
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
// code block to be executed
}
Example
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:
Example
while (i < 10) {
text += "The number is " + i;
i++;
}
43
JavaScript HTML DOM
44
JavaScript HTML DOM
45
JavaScript HTML DOM
With the object model, JavaScript gets all the power it needs
to create dynamic HTML:
JavaScript can change all the HTML elements in the page
JavaScript can change all the HTML attributes in the page
JavaScript can change all the CSS styles in the page
JavaScript can remove existing HTML elements and
attributes
JavaScript can add new HTML elements and attributes
JavaScript can react to all existing HTML events in the page
JavaScript can create new HTML events in the page
46
What is the HTML DOM?
47
What is the HTML DOM?
48
Finding HTML Elements
Method Description
document.getElementById(id) Find an element by
element id
document.getElementsByTagName(name) Find
elements by tag name
document.getElementsByClassName(name)
Find elements by class name
49
Changing HTML Elements
Property Description
element.innerHTML = new html content Change
the inner HTML of an element
element.attribute = new value Change the
attribute value of an HTML element
element.style.property = new style Change the
style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the
attribute value of an HTML element
50
Adding and Deleting Elements
Method Description
document.createElement(element) Create an HTML
element
document.removeChild(element) Remove an HTML
element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML
element
document.write(text) Write into the HTML output
stream
51
Link exercise
https://www.w3schools.com/js/exercise_js.asp?fil
ename=exercise_js_variables1
https://techbootcamps.utexas.edu/blog/best-way
s-to-learn-javascript/
52