[Go to site: main page, start]

0% found this document useful (0 votes)
3 views75 pages

JavaScript Basics and Applications Guide

The document provides an overview of JavaScript, a dynamic scripting language used to enhance web pages with interactivity and functionality. It covers fundamental concepts such as data types, variables, operators, control structures, and methods for manipulating HTML content. Additionally, it explains the advantages of JavaScript, including reduced server interaction and immediate user feedback.

Uploaded by

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

JavaScript Basics and Applications Guide

The document provides an overview of JavaScript, a dynamic scripting language used to enhance web pages with interactivity and functionality. It covers fundamental concepts such as data types, variables, operators, control structures, and methods for manipulating HTML content. Additionally, it explains the advantages of JavaScript, including reduced server interaction and immediate user feedback.

Uploaded by

elkhwarzmy720
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JavaScript (JS)

Outline:
 Introduction to JavaScript  If statements, switch case

 Advantages of JavaScript  Loops

 JS First Program  Functions

 Comments  Window’s object methods

 Position of JavaScript in
HTML document

 JS and HTML Content

 JavaScript Output

 Data types

 Variables

 Operators
Introduction to JavaScript
 JavaScript is a scripting language which is used to
enhance the functionality and appearance of web pages.
 JavaScript is a dynamic computer programming
language.
 It is lightweight and most commonly used as a part of
web pages, whose implementations allow client-side
script to interact with the user and make dynamic
pages.
 It is an interpreted programming language with
object-oriented capabilities.
Advantages of JavaScript

 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.
 Increased interactivity: You can create interfaces that
react when the user hovers over them with a mouse or
activates them via the keyboard.
 Richer interfaces: You can use JavaScript to include such
items as drag- and-drop components and sliders to give a
Rich Interface to your site visitors.
JS First Program
 Display a Line of Text with JavaScript in a Web Page
 A simple script that displays the text
 "Welcome to JavaScript Programming!" in the HTML5 document.
 All major web browsers contain JavaScript interpreters, which process the
commands written in JavaScript.
<html>
<!-- [Link] -->
<head>
<title>
A First Program in JavaScript
</title>
<script type = "text/javascript">
[Link]( "<h1> Welcome to JavaScript Programming! </h1>");
</script>
</head>
<body>
</body>
</html>

Script result
JS First Program
 Often, JavaScript appear in the <head> section of the HTML document
 The browser interprets the contents of the <head> section first
 In HTML, the JavaScript code is inserted between <script> and
</script> tags.
 A string of characters can be contained between double quotation (") marks
(also called a string literal)
 JavaScript is a case-sensitive language.
 It is a good programming practice to use semicolons.
Comments
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in java

/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in java
*/
//-->
</script>

The HTML comment closing sequence --> is not recognized by


JavaScript so it should be written as //-->.
Position of JavaScript in HTML document
 There is a flexibility given to include JavaScript code
anywhere in an HTML document.
 However the most preferred ways to include JavaScript
in an HTML file are as follows:
 Script in <head>...</head> section.

 Script in <body>...</body> section.

 Script in <body>...</body> and <head>...</head> sections.

 Script in an external file and then include in <head>...</head>


section.
Position of JavaScript in HTML document
 Script in head section
<html>
<head>
<title>JavaScript in Head</title>
<script>
// This is a simple JavaScript function
function greet() {
alert("Hello, welcome to our website!");
}
// Call the function when the page loads
[Link] = greet;
</script>
</head>
<body>
<h1>Welcome to My Website</h1>
<p>Enjoy your stay!</p>
</body>
</html>
Position of JavaScript in HTML document
 Script in body section
JS and HTML Content
 What JavaScript can do:
can change the content of an HTML element:

<!DOCTYPE html>
<html>
<body>
<h1>My First JavaScript</h1>
<p>JavaScript can change the content of an HTML element:</p>
<button type="button" Me!</button>
<p id="demo">This is a demonstration.</p>
<script>
function myFunction() {
[Link]("demo").innerHTML = "Hello JavaScript!";
}
</script>
</body>
</html>
JS and HTML Content
 What JavaScript can do:
JS can change HTML attributes :
<html>
<body>
<h1>My First JavaScript</h1>
<p>Here, a JavaScript changes the value of the src (source) attribute of an image.</p>
<script>
function light(sw) {
var pic;
if (sw == 0) {
pic = "[Link]"
} else {
pic = "[Link]"
}
[Link]('myImage').src = pic;
}
</script>
<img id="myImage" src="[Link]" width="100" height="180">
<p>
<button type="button" > <button type="button" > </p>
</body>
</html>
JS and HTML Content
 What JavaScript can do:
JS can change styles :

<html>
<body>
<h1>My First JavaScript</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<script>
function myFunction() {
[Link]("demo").[Link] = "25px";
[Link]("demo").[Link] = "red";
[Link]("demo").[Link] = "yellow";
}
</script>
<button type="button" Me!</button>
</body>
</html>
JS and HTML Content
 What JavaScript can do:
JS can writes into an HTML element with id:

<!DOCTYPE html>
<html>
<body>
<h2>Use JavaScript to Change Text</h2>
<p>This example writes "Hello JavaScript!" into an HTML element with id="demo":</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
</body>
</html>
JS and HTML Content
 What JavaScript can do:
JS can defines an alternate content to be displayed to users that
have disabled scripts in their browser or have a browser that doesn't
support scripts :
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello JavaScript!";
</script>
<noscript>
Sorry, your browser does not support JavaScript!
</noscript>
<p>A browser without support for JavaScript will show
the text written inside the noscript element.</p>
</body>
</html>
JS and HTML Content
 What JavaScript can do:
JS Can Show HTML Elements:

<!DOCTYPE html>
<html>
<body>
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can show hidden HTML elements.</p>
<p id="demo" style="display:none">Hello JavaScript!</p>
<button
type="button" Me!
</button>
</body>
</html>
JavaScript Output
 JavaScript Display Possibilities

 Writing into an HTML element, using innerHTML or innerText.

 Writing into the HTML output using [Link]().

 Writing into an alert box, using [Link]().

 Writing into the browser console, using [Link]().


JavaScript Output
 Using innerHTML
 To access an HTML element, you can use the [Link](id)
method.

 Use the id attribute to identify the HTML element

 And use the innerHTML property to change the inner text of the HTML
element:

<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "<h2>Hello World</h2>";
</script>
</body>
</html>
JavaScript Output
 Using innerText
 To access an HTML element, use the [Link](id) method.

 Use the id attribute to identify the HTML element

 Then use the innerText property to change the inner text of the HTML
element:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
[Link]("demo").innerText = "Hello World";
</script>
</body>
</html>
JavaScript Output
 Using [Link]()
 For testing purposes, it is convenient to use [Link]():
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>
 Using [Link]() after an HTML document is loaded, will delete all
existing HTML:
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<button type="button" + 6)">Try it</button>
</body>
</html>
JavaScript Output
 Using [Link]()
 We can use an alert box to display data:
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>

 window keyword is optional


<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
JavaScript Output
 Using [Link]()
 The console object provides access to the browser's debugging console.

 The console object is a property of the window object.

 For debugging purposes, we can call the [Link]() method in the


browser to display data.

 Syntax: [Link] or just console

<!DOCTYPE html>
<html>
<body>
<script>
[Link](5 + 6);
</script>
</body>
</html>
JavaScript Output
 JavaScript Print
 JS does not have any print object or print methods.

 You cannot access output devices from JavaScript.

 The only exception is that we can call the [Link]() method in the
browser to print the content of the current window.

<!DOCTYPE html>
<html>
<body>
<h2>The [Link]() Method</h2>
<p>Click the button to print the current page.</p>
<button this page</button>
</body>
</html>
Data types
 JavaScript has the following Data types:
 String let color = "Yellow";
 Number let length = 16;
 Bigint let x = BigInt("123456789012345678901234567890");
 Boolean let x = true;
 Undefined let car;
 Null let car=“”
 Object const person = {firstName:“Ali", lastName:“Gad"};
Data types
 The Concept of Data Types:
let x = 16 + "Volvo"; ≡ let x = "16" + "Volvo";
let x = "Volvo" + 16 ; ≡ let x = "Volvo" + "16" ;
let x = 16 + 4 + "Volvo"; ≡ let x = 20 + "Volvo" ;
let x = "Volvo" + 16 + 4; ≡ let x = "Volvo" + “16” + “4” ;

let x; // Now x is undefined


x = 5; // Now x is a Number
x = "John"; // Now x is a String

// Using double quotes:


let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';

// Single quote inside double quotes:


let answer1 = "It's alright";
Data types
 The Concept of Data Types:
// Single quotes inside double quotes:
let answer2 = "He is called 'Johnny'";

// Double quotes inside single quotes:


let answer3 = 'He is called "Johnny"';

// With decimals:
let x1 = 34.00;

// Without decimals:
let x2 = 34;

let car; // Value is undefined, type is undefined

let car = ""; // The value is "", empty string


// an empty string has both a legal value and a type.
Variables
 Before you use a variable in a JavaScript program, you
must declare it.
 JavaScript uses the keywords var, let and const to declare
variables.

<script type = "text/javascript">


var name;
</script>
Variables
 JavaScript let

 Variables declared with let have Block Scope

Variables declared inside a { } block cannot be accessed from outside the block:
{
let x = 2;
}
// x can NOT be used here

 Variables declared with let must be Declared before use

carName = "Saab"; // error


let carName = "Volvo";

 Variables declared with let cannot be Re-declared in the same scope

let x = 10;
// Here x is 10
{
let x = 2;
// Here x is 2
}
// Here x is 10
Variables
 JavaScript var
 Variables declared with the var always have Global Scope.
Variables declared inside a { } block cannot be accessed from outside the block:
{
var x = 2;
}
// x can be used here

 Variables can be used before it is declared


carName = "Saab";
var carName = "Volvo";

 Variables declared with var can be Re-declared


var x = 10;
// Here x is 10
{
var x = 2;
// Here x is 2
}
// Here x is 2
Variables
 JavaScript const
 Const used to declare a constant value
 Variables declared with const have Block Scope.
Variables declared inside a { } block cannot be accessed from outside the block:
{
const x = 2;
}
// x cannot be used here

 Variables declared as const cannot be reassigned


const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error

 Variables declared as const cannot be Re-declared


const x = 10;
// Here x is 10
{
const x = 2;
// Here x is 2
}
// Here x is 10
Variables
 JavaScript const (Arrays)
 It does not define a constant value. It defines a constant reference to a
value..
 We can change the elements of a constant array:
<html>
<body>
<h2>JavaScript const</h2>
<p>Declaring a constant array does NOT make the elements unchangeable:</p>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"]; // Create an Array:
cars[0] = "Toyota"; // Change an element:
[Link]("Audi"); // Add an element:
[Link]("demo").innerHTML = cars; // Display the Array:
</script>
</body>
</html>

 We can NOT reassign the array:


const cars = ["Saab", "Volvo", "BMW"];

cars = ["Toyota", "Volvo", "Audi"]; // ERROR


Variables
 JavaScript const (Objects)
 It does not define a constant value. It defines a constant reference to a
value..
 We can change the elements of a constant object:
<html>
<body>
<h2>JavaScript const</h2>
<p>Declaring a constant object does NOT make the objects properties unchangeable:</p>
<p id="demo"></p>
<script>
const car = {type:"Fiat", model:"500", color:"white"}; // Create an object:
[Link] = "red"; // Change a property:
[Link] = “Ahmed"; // Add a property:
// Display the property:
[Link]("demo").innerHTML = "Car owner is " + [Link];
</script>
</body>
</html>

 We can NOT reassign the object:


const car = {type:"Fiat", model:"500", color:"white"};
car = {type:"Volvo", model:"EX60", color:"red"}; // ERROR
Variables
 JavaScript const (Objects)
 The delete operator deletes a property from an object:

<html>
<body>
<h1>JavaScript Operators</h1>
<h2>The delete Operator</h2>
<p>The delete operator deletes a property from an object:</p>
<p id="demo"></p>
<script>
const person = {
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
delete [Link];
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>
Operators
JavaScript supports the following types of operators.
 Arithmetic Operators

 Assignment Operators

 Comparison Operators

 String Operators

 Logical Operators

 Bitwise Operators

 Ternary Operators

 Type Operators
Operators
 Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation
/ Division
% Modulus (Division Remainder)
++ Increment
-- Decrement
Operators
 Assignment Operators

Operator Example Same As


= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Operators
 Comparison Operators
Operator Description
== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

The difference between == and ===:

[Link](5 == '5'); // true (string '5' is converted to number 5)


[Link](null == undefined); // true (special case in JavaScript)

[Link](5 === '5'); // false (number !== string)


[Link](5 === 5); // true (same type and value)
Operators
 String Operators
All the comparison operators above can also be used on strings:

Operator Description
== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator
Operators
 Logical Operators

Operator Description
Logical AND
&& If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.
Logical OR
|| If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
Logical NOT
Reverses the logical state of its operand. If a condition is true, then the Logical
! NOT operator will make it false.
Ex:! (A && B) is false.
Operators
 Bitwise Operators

Operator Description Example Same as Result Decimal

AND 5&1 0101 & 0001 0001 1


&
OR 5|1 0101 | 0001 0101 5
|
NOT ~5 ~0101 1010 10
~
XOR 5^1 0101 ^ 0001 0100 4
^
left shift 5 << 1 0101 << 1 1010 10
<<
right shift 5 >> 1 0101 >> 1 0010 2
>>
unsigned right shift 5 >>> 1 0101 >>> 1 0010 2
>>>
Operators
 Ternary Operators
 Operator takes three operands: a condition followed by a question mark
(?), then an expression to execute if the condition is truth followed by a
colon (:), and finally the expression to execute if the condition is false.
 This operator is frequently used as an alternative to an if...else statement.

 Syntax:

condition ? exprIfTrue : exprIfFalse

 Example:

function getFee(isMember) {
return isMember ? "$2.00" : "$10.00";
}
[Link](getFee(true)); // Expected output: "$2.00“
[Link](getFee(false)); // Expected output:"$10.00“
[Link](getFee(null)); // Expected output: "$10.00"
Operators
 Ternary Operators Conditional chains
 The ternary operator is right-associative, which means it can be "chained" in
the following way, similar to an if … else if … else if … else chain:
 Syntax:
function example() {
if (condition1) {
return value1;
function example() { } else if (condition2) {
return condition1 ? value1 return value2;
: condition2 ? value2
: condition3 ? value3
: value4;
≡ } else if (condition3) {
return value3;
} } else {
return value4;
}
}
Operators
 Ternary Operators Conditional chains
 The ternary operator is right-associative, which means it can be "chained" in
the following way, similar to an if … else if … else if … else chain:
 Example:
<html>
<body>
<script type="text/javascript">
var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
[Link](beverage);
</script>
</body>
</html>

let score = 85;


let grade = score >= 90 ? 'A' :
score >= 80 ? 'B' :
score >= 70 ? 'C' :
score >= 60 ? 'D' : 'F';
[Link]("Grade:", grade);
if...else Statement
 JavaScript supports conditional statements which are used to perform
different actions based on different conditions.

 The following flow chart shows how the if-else statement works.

let age = 20;

if (age >= 18) {


[Link]("You are an adult.");
} else {
[Link]("You are a minor.");
}
if...else Statement
if...else Statement
if...else Statement
 JavaScript supports the following forms of if..else statement

 if statement

 if...else statement

 if...else if... statement.

 However, this may not always be the best


solution, especially when all of the branches
depend on the value of a single variable.
 You can use a switch statement which handles
exactly this situation, and it does so more
efficiently than repeated if...else if statements.
switch statement
Loops
While Loop
 While writing a program, you may encounter a situation where you need to
perform an action over and over again. In such situations, you would need to
write loop statements to reduce the number of lines.

let count = 1;

while (count <= 5) {


[Link]("Count is: " + count);
count++;
}
Loops
While Loop
Loops
For Loop
It includes the following three important parts
 The loop initialization where we initialize our counter to a starting value.
The initialization statement is executed before the loop begins.
 The test statement which will test if a given condition is true or not. If
the condition is true, then the code given inside the loop will be executed,
otherwise the control will come out of the loop.
 The iteration statement where you can increase or decrease your counter.

for (let i = 1; i <= 5; i++) {


[Link]("Iteration number: " + i);
}
Loops
For Loop
Loops
Do-while Loop
 Tests the loop-continuation condition after the loop body executes

 The loop body always executes at least once

let number = 1;

do {
[Link]("Number is:", number);
number++;
} while (number <= 3);
Loops
Do-while Loop
Functions
 A JavaScript function is a block of code designed to perform a
particular task. It is reusable code which can be called anywhere in
your program. This eliminates the need of writing the same code again
and again.

 You have seen functions like alert() and write() in the earlier part.

 The most common way to define a function in JavaScript is by using


the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded
by curly braces.

 Example:

<script type "text/javascript">


<!-- function sayHello() {
alert("Hello there");
} //-->
</script>
Functions
Calling a Function
 To invoke a function somewhere later in the script, you would simply need
to write the name of that function as shown in the following code.
Functions
Calling a Function
 The function is called explicitly for the
code in its body to execute
 Return statement passes information
from inside a function back to the point
in the program where it was called
Functions
User define function:
<html> </script>
<!-- [Link] --> </head>
<head> <body>
<script type="text/javascript"> Find the largest number and Mininum number:
function max(){ <button type = "button" >max</button>
var a,b,c,x, y, z, max; <button type = "button" >min</button>
a=[Link]("enter first number",0.0); </body>
b=[Link]("enter sec number"); </html>
c=[Link]("enter third number");
x=parseFloat(a);
y=parseFloat(b);
z=parseFloat(c);
max=[Link](x, [Link](y,z)); //predefined function
[Link]("Maximum of 3 numbers= "+max);
}
function minimum(){
var a, b, c, x, y, z, max, min;
a=[Link]("enter first number",0.0);
b=[Link]("enter sec number");
c=[Link]("enter third number");
x=parseFloat(a);
y=parseFloat(b);
z=parseFloat(c);
min=mini(x,y,z);
[Link]("min= "+min);
}
function mini(x,y,z){
var mi=[Link](x, [Link](y,z)); //predefined function
return mi;
}
Window
 The window object represents an open window in a browser.
 If a document contain frames (<iframe> tags), the browser
creates one window object for the HTML document, and one
additional window object for each frame.
 Some window Object Properties:

Property Description
closed Returns a boolean true if a window is closed.
console Returns the Console Object for the window.
See also The Console Object.
document Returns the Document object for the window.
See also The Document Object.
Window
 Window Object Methods
Property Description Example
addEventListener() Attaches an event handler to [Link](event, function)
the window
alert() Displays an alert box with a alert("Hello! I am an alert box!!");
message and an OK button
confirm() Displays a dialog box with a confirm("Press a button!");
message and an OK and a Cancel
button
console() [Link]("You made a mistake");
print() Prints the content of the <button this
current window page</button>
prompt() Displays a dialog box that let stdName= prompt("What's yourname?", “ali");
prompts the visitor for input
stop() Stops the window from loading [Link]();
resizeBy() Resizes the window by the
specified pixels
resizeTo() Resizes the window to the
specified width and height
Window
 Prompt method <html>
<body>
Example: <h1>The Window Object</h1>
<h2>The prompt() Method</h2>
<p>Click the button to ask for your favorite drink.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let favDrink = prompt("What's your favorite drink?", "Coca-Cola");
switch(favDrink) {
case "Coca-Cola":
text = "Excellent choice. Coca-Cola is good for your soul.";
break;
case "Pepsi":
text = "Pepsi is my favorite too!";
break;
case "Sprite":
text = "Really? Are you sure the Sprite is your favorite?";
break;
default:
text = "I have never heard of that one..";
}
[Link]("demo").innerHTML = text;
}
</script>
</body>
</html>
Events
 The structure of an HTML document as a tree-like structure, allowing
developers to access, manipulate, and update the elements, attributes, and
content of the document dynamically.
 HTML allows JavaScript to react to HTML events by any element in the tree:
Events
 A JavaScript can be executed when an event occurs, like when a user clicks
on an HTML element.
 To execute code when a user clicks on an element, add JavaScript code to an
HTML event attribute: > <html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onclick Attribute</h2>
<h2 on this text!</h2>
</body>
</html>
 Examples of HTML events:
 When a user clicks the mouse
 When a web page has loaded
 When an image has been loaded
 When the mouse moves over an element
 When an input field is changed
 When an HTML form is submitted
 When a user strokes a key
Events
Mouse Events:

click: Triggered when the user clicks on an element.


dblclick: Triggered when the user double-clicks on an element.
mousedown: Triggered when the user presses a mouse button over an element.
mouseup: Triggered when the user releases a mouse button over an element.
mousemove: Triggered when the user moves the mouse pointer over an element.
mouseover: Triggered when the user moves the mouse pointer onto an element.
mouseout: Triggered when the user moves the mouse pointer out of an element.

Window Events

load: Triggered when the whole page has loaded.


resize: Triggered when the browser window is resized.
scroll: Triggered when the user scrolls the element.
Document addEventListener()
 When an HTML document is loaded into a web browser, it becomes
a document object.
 The document object is the root node of the HTML document.
 The document object is a property of the window object.
 The document object is accessed with:
[Link] or just document
 Add a click event to the document we use addEventListener method:

 Simple Syntax:

[Link](event, function)

 Example:

[Link]("click", myFunction);

function myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
Document addEventListener()
<html>
<body>
<h1>The Document Object</h1>
<h2>The addEventListener() Method</h2>
<p>This example adds many events on the document.</p>
<p id="demo"></p>
<script>
[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);
function myFunction() {
[Link]("demo").innerHTML = "Moused over!"
}
function mySecondFunction() {
[Link]("demo").innerHTML = "Clicked!<br>"
}
function myThirdFunction() {
[Link]("demo").innerHTML = "Moused out!<br>"
}
</script>
</body>
</html>
Element addEventListener()
 Add a click event to the document:
 Simple Syntax:

[Link](event, function)

 Example:

[Link]("click", myFunction);

function myFunction() {
[Link]("demo").innerHTML = "Hello World";
}

[Link]("click", myFunction() {
[Link]("demo").innerHTML = "Hello World";
}
Element addEventListener()
Example: add many events on the same element (button).

<html>
<body>
<h1>The Element Object</h1>
<p>Attach a click event to a button:</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
const element = [Link]("myBtn");
[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);
function myFunction() {
[Link]("demo").innerHTML = "Moused over!"}
function mySecondFunction() {
[Link]("demo").innerHTML = "Clicked!<br>"}
function myThirdFunction() {
[Link]("demo").innerHTML = "Moused out!<br>"}
</script>
</body>
</html>
Element addEventListener()
Example: add many events on the same element (button).

<html>
<body>
<h1>The Element Object</h1>
<p>Attach a click event to a button:</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
const element = [Link]("myBtn");
[Link]("mouseover",
function(){[Link]("demo").innerHTML = "Moused over!";});
[Link]("click",
function(){[Link]("demo").innerHTML = "Clicked!<br>";})
[Link]("mouseout",
function(){[Link]("demo").innerHTML = "Moused out!<br>";})
</script>
</body>
</html>
Quiz
Create HTML file that display counter (press +/- button increment/decrement counter)
<html >
<head> </style>
<title>Counter</title> </head>
<style> <body>
body{ <section id="counter">
font-family: sans-serif; <div>
background-color: black; <h1 id="counterDisplay">0</h1>
} <div id="counterControls">
#counter { <button id="counterAdd">+</button>
display: flex; <button id="counterSub">-</button>
width: 100%; </div>
justify-content: center; </div>
} </section>
#counterDisplay { <script>
font-size: 4 rem; var total=0
text-align: center; const element =
color: white; [Link]("counterAdd");
} [Link]("click",
#counter button {
border: 0; function(){[Link]("counterDisplay").inne
padding: 0.5rem 1rem; rHTML = total++;});
font-size: 2rem; const element1 =
cursor: pointer; [Link]("counterSub");
} [Link]("click",
#counterAdd {
background-color: green; function(){[Link]("counterDisplay").inne
} rHTML = --total;});
#counterSub { </script>
background-color:brown; </body>
} </html> [Link]
Quiz
 Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
Quiz
 Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
<html>
<head>
<title>Simple Calculator</title>
<style>
body {
background-color: #f0f0f0;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.calculator {
background-color: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
text-align: center;
width: 300px;
}
input[type="number"] {
width: 80%;
padding: 8px;
margin: 10px 0;
font-size: 16px;
}
Quiz
 Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.
select, button {
padding: 10px;
margin-top: 10px;
font-size: 16px;
width: 85%;
}
#result {
margin-top: 20px;
font-size: 18px;
color: #333;
font-weight: bold;
}
</style>
</head>
<body>
<div class="calculator">
<h2>Simple Calculator</h2>
<input type="number" id="num1" placeholder="Enter first number"><br>
<input type="number" id="num2" placeholder="Enter second number"><br>
<select id="operator">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select><br>
<button > Quiz
 Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.

<div id="result"></div>
</div>
<script>
function calculate() {
const num1 = parseFloat([Link]("num1").value);
const num2 = parseFloat([Link]("num2").value);
const operator = [Link]("operator").value;
const resultDisplay = [Link]("result");
if (isNaN(num1) || isNaN(num2)) {
[Link] = "Please enter valid numbers.";
[Link] = "red";
return;
}
let result;
if (operator === "/" && num2 === 0) {
[Link] = "Cannot divide by zero";
[Link] = "red";
return;
}
Quiz
 Build a working calculator that can do addition, subtraction, multiplication, and division
between two numbers.

switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
[Link] = "Result: " + result;
[Link] = "#333";
}
</script>
</body>
</html>
JavaScript Global Methods and Properties
 The JavaScript global properties and methods can be used with all
JavaScript objects.
 Since these methods are global, and global the object is the browser window,
these methods are actually window methods:
isNaN() is the same as [Link]().

Name Description
Infinity A numeric value that represents positive/negative infinity
isFinite() Determines whether a value is a finite, legal number
isNaN() Determines whether a value is an illegal number
NaN "Not-a-Number" value
Number() Converts an object's value to a number
parseFloat() Parses a string and returns a floating point number
parseInt() Parses a string and returns an integer

String() Converts an object's value to a string


undefined Indicates that a variable has not been assigned a value

You might also like