0% found this document useful (0 votes)
2 views

Webprog-js

Uploaded by

Broli Tiako
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Webprog-js

Uploaded by

Broli Tiako
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

HTML- CSS- JS COURSE

Java Script langage

Lecturer : TABUEU FOTSO Laurent Cabrel /PhD Data mining


Introduction

JavaScript is the world's most popular


programming language.
JavaScript is the programming language of the
Web.

2
What can JavaScript do?

Use <!DOCTYPE html>


<html>
<body>

<h2>What Can JavaScript


Do?</h2>

<p id="demo">JavaScript can


change HTML content.</p>

<button type="button"
onclick='document.getElementById(
"demo").innerHTML = "Hello
JavaScript!"'>Click Me!</button>

</body>
</html>

3
Change attribute value

<p>JavaScript can change HTML attribute values.</p>

<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>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<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

The <script> Tag


In HTML, JavaScript code is inserted between <script> and </script> tags.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
</body>
</html>

8
JavaScript Functions and Events

A JavaScript function is a block of JavaScript code, that


can be executed when "called" for.
For example, a function can be called when an event
occurs, like when the user clicks a button.

You can place any number of scripts in an HTML


document. Scripts can be placed in the <body>, or in
the <head> section of an HTML page, or in both.

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

External scripts are practical when the same


code is used in many different web pages.
JavaScript files have the file extension .js.
To use an external script, put the name of the
script file in the src (source) attribute of a
<script> tag:
Example
<script src="myScript.js"></script> in body or
head element.

12
External JavaScript Advantages

Placing scripts in external files has some advantages:

It separates HTML and code


It makes HTML and JavaScript easier to read and maintain
Cached JavaScript files can speed up page loads
To add several script files to one page - use several script
tags:
Example
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

13
External JavaScript Advantages

External References
An external script can be referenced in 3 different
ways:

With a full URL (a full web address)


With a file path (like /js/)
Without any path

14
JavaScript Output

JavaScript can "display" data in different ways:

Writing into an HTML element, using innerHTML.


Writing into the HTML output using
document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using
console.log().

15
Using innerHTML

To access an HTML element, JavaScript can use the


document.getElementById(id) method. The id attribute
defines the HTML element. The innerHTML property
defines the HTML content.

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

A computer program is a list of "instructions" to be "executed" by a


computer. In a programming language, these programming
instructions are called statements.
A JavaScript program is a list of programming statements.
In HTML, JavaScript programs are executed by the web browser.
JavaScript statements are composed of: Values, Operators,
Expressions, Keywords, and Comments.
Most JavaScript programs contain many JavaScript statements. The
statements are executed, one by one, in the same order as they are
written.
JavaScript programs (and JavaScript statements) are often called
JavaScript code.
Semicolons separate 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

JavaScript statements can be grouped together in code blocks,


inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed
together.
One place you will find statements grouped together in blocks, is
in JavaScript functions:
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are
you?";
}

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

JavaScript syntax is the set of rules, how JavaScript programs are


constructed:
// How to create variables:
var x; let y;
// How to use variables:
X = 5; y = 6; let z = x + y;
JavaScript Values
The JavaScript syntax defines two types of values:
Fixed values
Variable values
Fixed values are called Literals.
Variable values are called Variables.

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?

Always declare JavaScript variables with var,let, orconst.

The var keyword is used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 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

JavaScript Type 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?

In JavaScript, the this keyword refers to an object.


Which object depends on how this is being invoked (used or called).
The this keyword refers to different objects depending on how it is
used:
In an object method, this refers to the object.
Alone, this refers to the global object.
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any object.

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.

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
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

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:

Syntax day = "Sunday";

switch(expression) {
break;

case 1:

case x: day = "Monday";

break;
// code block case 2:

break; day = "Tuesday";

break;
case y: case 3:

// code block day = "Wednesday";

break;

break; case 4:

default: day = "Thursday";

break;

// code block case 5:

} day = "Friday";

break;

case 6:

41 day = "Saturday";

}
JavaScript switch

The For Loop <html>


<body>
The for loop has the following syntax:
for (statement 1; statement 2; <h2>JavaScript For Loop</h2>
statement 3) {
// code block to be executed <p id="demo"></p>

} <script>
const cars = ["BMW", "Volvo", "Saab", "Ford"];

Statement 1 is executed (one time) let i, len, text;

before the execution of the code block. for (i = 0, len = cars.length, text = ""; i < len; i+
+) {
text += cars[i] + "<br>";

Statement 2 defines the condition for }


executing the code block. document.getElementById("demo").innerHTML
= text;
</script>
Statement 3 is executed (every time)
after the code block has been executed. </body>
</html>

42
JavaScript switch

The While Loop

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

With the HTML DOM, JavaScript can access and change


all the elements of an HTML document.
When a web page is loaded, the browser creates a
Document Object Model of the page.
The HTML DOM model is constructed as a tree of
Objects:
The HTML DOM Tree of Objects
DOM HTML tree

44
JavaScript HTML DOM

The HTML DOM Tree of Objects

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?

The HTML DOM is a standard object model and


programming interface for HTML. It defines:

The HTML elements as objects


The properties of all HTML elements
The methods to access all HTML elements
The events for all HTML elements

In other words: The HTML DOM is a standard for


how to get, change, add, or delete HTML elements.

47
What is the HTML DOM?

In the DOM, all HTML elements are defined as objects.

The programming interface is the properties and methods of each object.


A property is a value that you can get or set (like changing the content
of an HTML element).
A method is an action you can do (like add or deleting an HTML
element).
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
In the example above, getElementById is a method, while
innerHTML is a property.

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

You might also like