CHAPTER Four JS_Part 2 (2)
CHAPTER Four JS_Part 2 (2)
1
JavaScript Array
Creating an Array
Syntax:
let array-name = [item1, item2, ...];
Using the new keyword
Example:
let cars = ["Saab", "Volvo", "BMW"];
let cars = new Array("Saab", "Volvo", "BMW");
Array can hold different objects/datatypes
Array index starts with 0
2
Accessing Array Elements
Arrays use numbers to access its "elements”
let person = ["John", "Doe", 46];
person[0] returns John
Objects use names to access its "members".
let person = { firstName:"John", lastName:"Doe",
age:46};
person.firstname returns John
3
Array Properties and Methods
The length Property
returns the length of an array, it is dynamic (it updates automatically)
Example
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length;
It is also possible to change the length property to
truncate an array
Example fruits.length=2,
results in fruits=["Banana", "Orange“];
Adding Array Elements
The easiest way to add a new element to an array is using the push method:
Example
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon");
Sorting Array Elements
let y = fruits.sort(); // sort fruits in alphabetical order
4
Array Properties and Methods
pop() – removes the last element
let y = [1,2,3,4];
y.pop(); results in y=[1,2,3]
unshift()- add elements to the beginning
let y = [1,2,3,4];
y.unshift(10); results in y=[10,1,2,3,4]
shift() – removes the first element
let y = [1,2,3,4];
y.shift(); results in y=[2,3,4]
splice()- adds or removes elements at specific index
let y = [10, 20, 30, 40];
splice(startIndex, deleteCount, newElements)
y.splice(2,1,50,60); results in y=[10, 20, 50, 60, 40] 5
Array Properties and Methods
reverse() – reverse the array
let y = [10,20,30,40];
y.reverse(); results in y=[40,30,20,10]
concat()- merge two or more arrays
let y = [1,2,3,4], x=[10,20,30];
let z= y.concat(x); results in z=[1,2,3,4,10,20,30]
slice() – extract a portion of an array
let y = [10,20,30,40];
let part = y.slice(1,3); results in part=[20,30]
include()- checks if an element exists
let y = [10, 20, 30, 40];
Let z=y.include(40); returns true while z=y.include(70)
returns false 6
Array Properties and Methods
indexOf() – returns the first index of an element
let y = [10,20,30,40];
y.indexOf(30); returns 2
lastIndexOf()- returns the last index of an element
let y = [10,20,30,20];
let z= y.lastIndexOf(20); results in z=3
join() – coverts an array to a string
let y = [“Hello”, “World”];
let z=y.join(“ ”); returns z=“Hello World”
7
JavaScript Functions
Function Syntax
function name(para1, para2) var x = myFunction(4, 3);
function myFunction(a, b)
{ code to be executed }
{ return a * b; }
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)
Function 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. 8
JavaScript Functions
Function parameters and arguments – functions can accept and return
values
a) Default Parameters: if a parameter is not provided, JavaScript assigns
the default value
Example:
function greet(name = "Guest") {
return `Hello, ${name}!`; }
console.log(greet());
b) Rest Parameters (...): used to accept multiple arguments as an array
Example
function printNames(...names) {
console.log("Names:", names); }
printNames("Alice", "Bob", "Charlie", "David");
Return statement: a function can return a value using the return keyword
Without return, the function returns undefined
JavaScript Functions
Types of Functions in JavaScript
a) Function Declaration (Named Function)-A function declared using the
function keyword
Example:
function add(a, b)
{
return a + b;
}
console.log(add(5, 3));
b) Function Expression – a function stored in a variable
Example:
const multiply = function(a, b)
{
return a * b;
}; console.log(multiply(4, 2));
10
JavaScript Functions
Types of Functions in JavaScript
c) Arrow Functions (ES6) – a shorter syntax for writing function
Example:
const subtract = (a, b) => a - b;
console.log(subtract(10, 4));
If there’s a single parameter, parentheses are optional
If there are multiple lines in the function body, use curly braces
{ };
d) Anonymous Function – a function without a name, usually used as
an argument to other functions
Example
setTimeout( function() { console.log("Hello after 2 seconds"); },
2000); 11
JavaScript Functions
Types of Functions in JavaScript
e) Immediately Invoked Function Expression (IIFE) – a function
that runs as
soon as it is defined
Example:
(function() { console.log("This runs immediately!"); })();
f) Callback Functions – a function passed as an argument to
another function
Example:
function fetchData(callback) {
setTimeout(() => { callback("Data received"); }, 1000); }
fetchData((message) => console.log(message));
//Output (after 1 sec): Data received 12
JavaScript Functions
Types of Functions in JavaScript
g) Higher-Order Functions – a function that takes another function
as an argument or returns a function
Example:
function operate(operation, a, b)
{
return operation(a, b);
} console.log(operate((x, y) => x + y, 5, 3)); // Output: 8
13
JavaScript Functions
Function scope and hoisting
Local Scope: variables declared inside a function are not accessible
outside
Global Scope: variables declared outside are accessible inside
Hoisting: function declarations are hoisted, meaning they can be called
before
their definition
Example
sayHello();
function sayHello() { console.log("Hello!"); }
But function expressions are not hoisted
Example
console.log(square(5)); // Error
const square=function(x){ return x*x;};
JavaScript Events
HTML Events
An HTML event can be something the browser does, or
something a user does
Some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript
code, to be added to HTML elements
Syntax: <some-HTML-element some-event="some
JavaScript">
Ex: <button onclick=“displayDate();”>The time is?</button>
15
onload & onunload Events
The onload event The onunload event
occurs when an object has been occurs once a
loaded page has
is most often used with the unloaded
<body> element to execute a occurs when the
script once a web page has user navigates
completely loaded all content away from the page
can be used to check the visitor's (by clicking on a
browser type and browser version, link, submitting a
and load the proper version of the form, closing the
web page based on the information browser
can also be used to deal with
cookies
16
onsubmit Event
onsubmit event
occurs when you try to submit a form
often used to trigger a form validator function
In the following example: if validate() function returns
true, the form will be submitted, otherwise it will not
submit the data
<script>
function validation() {
all validation goes here .........
return either true or false }
</script>
<body>
<form method="POST" action="reg.asp" onsubmit="return
validate();">
.......
<input type="submit" value="Submit" />
</form> 17
onmouseover and onmouseout Event
The onmouseover event
triggers when you bring your mouse over any element and
The onmouseout event
triggers when you move your mouse out from an element
<script>
function over() {
document.getElementById("h2").innerHTML="Mouse
Over";}
function out() {
document.getElementById("h2").innerHTML="Mouse
Out";}
</script>
<body>
<div onmouseout="out();" onmouseover="over();" >
<h2 id="h2"> This is inside the division </h2> 18
onFocus, onBlur and onChange Events
The onFocus, onBlur and onChange events are often used with form elements
like <input>, <textarea>, and <select> to detect user interaction in the
validation of form fields
onFocus
triggers when an input filed gains focus (when the user clicks inside it)
used for highlighting or displaying hints
Example:
<input type="text“ id=“name" onFocus=“highlightField(this)”
placeholder=“Enter your name”>
<script>
function highlightField(element)
{
element.style.backgroundColor=“yellow”
}
</script>
When the input filed is clicked, its background turns yellow 19
onFocus, onBlur and onChange Events
onBlur
triggers when an input filed loses focus (when the user clicks
outside it)
used for validating or resetting styles
Example:
<input type="text" id="email"
onBlur="ValidateEmail()"
placeholder="Enter Email"/>
<p id="eror-msg" style="color: red;"> </p>
<script>
function ValidateEmail()
{
let email=document.getElementById("email").value;
let errorMsg=document.getElementById("eror-msg"); 20
onFocus, onBlur and onChange Events
if(!email.includes("@"))
{
errorMsg.textContent="Invalid email address!";
}
else
{
errorMsg.textContent=""; }
}
</script>
If the input does not contain “@”, it shows an error message when the
filed loses focus
21
onFocus, onBlur and onChange Events
onChange
triggers when an input value changes and loses focus
Works for text fields, checkboxes, dropdowns, and radio buttons
Example:
<select id="country" onchange="showSelection()">
<option value=" ">Select a country</option>
<option value="Ethiopia">Ethiopia</option>
<option value="Kenya">Kenya</option>
<option value="Djibutti">Djibutti</option>
<option value="Sudan">Sudan</option>
</select>
<p id="result"> </p>
<script>
function showSelection()
{
let country=document.getElementById("country").value;
document.getElementById("result").textContent="You selected:"+country;
}
</script>
When the user selects a country, it updates the <p> tag 22
Some HTML Events
Event Description Event Description
ontouchst Occurs when a finger is ondblclick occurs when the user
art placed on a touch double-clicks on an
screen element
onclick Occurs when the user oninput occurs when an
clicks an HTML element element gets user
input
onplay Occurs when the
media has been onsubmit occurs when a form is
started submitted
onoffline Occurs when the ondrag occurs when an
browser starts to work element is being
offline dragged
onkeydow Occurs when the user oncopy occurs when the user
n pushes a keyboard key copies the content of
Occurs when the an element
onload occurs when a page 23is
JavaScript Objects
JavaScript objects are containers
for named values
Accessing Object properties let person =
objectName.propertyName or { firstName:"Jo
objectName["propertyName"] h",
Example lastName:"Doe",
person.firstName or
id : 5566,
person[“firstName”]
Accessing Object Methods fullName :
objectName.methodName() function()
Example {
person.fullName(); return
this.firstName +
" " +
this.lastName;
24
JavaScript Strings
A string can be any text inside quotes. You can use
single or double quotes:
let carname = 'Volvo XC60';
You can use quotes inside a string, as long as they
don't match the quotes surrounding the string:
let answer = "It's alright";
The other solution is to use escape characters
let answer = ‘It\’s alright’;
Other escape characters: \’ , \” , \\ , \n, \t ….
The length of a string is found in the built-in property
length
answer.length 25
Some String Methods
Method Description
length Returns the length of the string
charAt(index) Returns the character at the specified index (position)
charCodeAt(idex) Returns the Unicode value of a character at an index,
“ABC”.charCodeAt(0) is 65
slice(start, end) Extract a part of a string(excluding end),
“Hello”.slice(1,4) is “ell”
substring(start, Similar to slice(), but it does not accept negative
end) indices
substr(start, Extract a substring starting from start, with length
length) characters “Hello World”.subustr(1,6); is “ello W”
replace(old, new) Replace first occurrence of old with new
split(separator) Splits a string into an array of substrings based on
separator “A, B, C”.split(“,”) gives [“A”,”B”,”C”] 26
Some String Methods
Method Description
replaceAll(old, Replace all occurrences of old with new “Hello
new) Hello”.replaceAll(“Hello”, “Hi”) gives “Hi Hi”
toUpperCase() Converts a string to uppercase letters
toLowerCase() Converts a string to lowercase letters
trim() Removes whitespace from both ends of a string
trimStart() Removes whitespace from the beginning of a string
trimEnd() Removes whitespace from the end of a string
34
Using the RegExp Object
In JavaScript, the RegExp object is a regular expression object
with predefined properties and methods.
Using the RegExp method test()
It searches a string for a pattern, and returns true or false,
depending on the result.
The following example searches a string for the character "e":
• let patt = /e/;
• patt.test("The best things in life are free!");
Using the RegExp method exec()
It searches a string for a specified pattern, and returns the
found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
• /e/.exec("The best things in life are free!"); \\returns
e 35
Using Regular Expressions
Using String search() With a Regular Expression
Use a regular expression to do a case-insensitive search for
"w3schools" in a string:
let str = "Visit W3Schools";
let n = str.search(/w3schools/i); //returns 6
Use String match() With a Regular Expression
searches a string for a match against a regular expression, and
returns the matches, as an Array object or returns null if no match
is found.
Syntax: string.match(regexp)
let str = "The rain in SPAIN stays mainly in the plain";
let res = str.match(/ain/gi);
The result in res will be:
ain,AIN,ain,ain
36
JavaScript Page Refresh
A web page can be refreshed using JavaScript
location.reload method
The method can be called automatically upon an
event or simply when the user clicks on a link
<a href="location.reload(true);">Refresh Page</a>
Auto Refresh
setTimeout() is a built-in JavaScript function which
can be used to execute another function after a
given time interval
<body
onload='setTimeout("location.reload(true);",2000);’> 37
JavaScript Page Redirection
There could be various reasons why you would like to
redirect a user from the original page
1. You did not like the name of your domain and you are
moving to a new one
2. You have built-up various pages based on browser
versions or their names or may be based on different
countries, then you can use client- side page redirection
to land your users on the appropriate page
3. Etc..
38
Page Redirection Cont’d
Auto redirect a page
<body onload="window.location='www.google.com';">
Auto redirect a page after sometime
<script>
function redirect()
{
window.location='www.google.com';
}
</script>
<body onload=“setTimeout(“redirect()“,5000);”>
<p>You will be redirected to google.com in 5
seconds.
</body> 39
Page Redirection Cont’d
To redirect visitors onto a different page based on their browser type
var browsername=navigator.appName;
if( browsername == "Netscape" )
{
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
window.location="http://www.location.com/ie.htm";
}
else
{
window.location="http://www.location.com/other.htm";
} 40
JavaScript Print Page
The JavaScript print function window.print() prints
the current web page when executed
You can call this function directly using the onclick
event as shown in the following example
<input type="button" value="Print"
onclick="window.print()" />
41
Cookies
What are cookies?
are small files which are stored on a user's computer
are designed to hold a modest amount of data specific to a particular client and
website
Each cookie is effectively a small lookup table containing pairs of (key, data)
values can be accessed either by a client side or server-side script language
Why do we need cookies?
When a web server has sent a web page to a browser, the connection is shut
down, and the server forgets everything about the user
Cookies were invented to solve the problem "how to remember information
about the user":
When a user visits a web page, his name can be stored in a cookie.
Next time the user visits the page, the cookie "remembers" his name.
When a browser request a web page from a server, cookies belonging to the page
is added to the request. This way the server gets the necessary data to
"remember" information about users 42
Cookies Cont’d
Cookies are a plain text data record of multiple
variable-length fields:
Expires: The date the cookie will expire. If this is blank,
the cookie will expire when the visitor quits the browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that set the
cookie. This may be blank if you want to retrieve the cookie
from any directory or page.
Secure: If this field contains the word "secure", then the
cookie may only be retrieved with a secure server. If this
field is blank, no such restriction exists.
Name: The name of the cookie
Value: The data that is going to be stored on the cookie
43
JavaScript Cookies
JavaScript can create, read, and delete cookies
with the document.cookie property.
With JavaScript, a cookie can be created like this:
document.cookie="username=John Doe;"
You can also add an expiry date. By default, the cookie
is deleted when the browser is closed:
document.cookie="username=John Doe;
expires=Thu,18 Dec 2013 12:00:00 UTC;" 44
JavaScript Cookies Cont’d
Read a Cookie with JavaScript
With JavaScript, cookies can be read like this:
var x = document.cookie;
document.cookie will return all cookies in one string much like:
cookie1=value; cookie2=value; cookie3=value;
Change a Cookie with JavaScript
With JavaScript, you can change a cookie the same way as you create
it:
document.cookie="username=John Smith; expires=Thu, 18 Dec 2013
12:00:00 UTC; path=/";
Delete a Cookie with JavaScript
Deleting a cookie is very simple. Just set the expires parameter to a passed
date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00
UTC";
45
Note that you don't have to specify a cookie value when you delete a cookie.
Set Cookie Example
function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert ("Enter some value!"); return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" +
cookievalue );
}
</script>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie"
onclick="WriteCookie();"/>
</form>
</body> 46
Read Cookie Example
<script type="text/javascript"> function ReadCookie(){
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++)
{name = cookiearray[i].split('=')[0]; value =
cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value); }
}
</script><body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form></body> 47
Introduction to jQuery
48
Introduction to jQuery
What is jQuery?
jQuery is a lightweight, "write less, do more",
JavaScript library.
The purpose of jQuery is to make it much
easier to use JavaScript on your website
jQuery takes a lot of common tasks that
require many lines of JavaScript code to
accomplish, and wraps them into methods that
you can call with a single line of code
49
Introduction to jQuery Cont’d
The jQuery library contains the following
features:
HTML/DOM manipulation
CSS manipulation
HTML event methods
Effects and animations
AJAX, Utilities
In addition, jQuery has plugins for almost any
task out there.
50
Adding jQuery to Web Pages
There are two ways to start using jQuery on
your web site
You can:
Download the jQuery library from
jQuery.com
Include jQuery from a CDN, like Google
51
Downloading jQuery
There are two versions of jQuery available for
downloading:
Production version - this is for your live
website because it has been minified and
compressed
Development version - this is for testing and
development (uncompressed and readable
code)
Both versions can be downloaded from
jQuery.com.
52
Embedding jQuery
The jQuery library is a single JavaScript file, and
you reference it with the HTML <script> tag
<head>
<script src="jquery-3.7.1.min.js
"></script>
</head>
53
jQuery from a CDN
jQuery CDN
If you don't want to download and host jQuery yourself, you
can include it from a CDN (Content Delivery Network).
Both Google and Microsoft host jQuery.
To use jQuery from Google or Microsoft, use one of the
following:
Google CDN:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jque
ry.min.js"> </script>
Microsoft CDN:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-
3.6.0.min.js"> </script> 54
jQuery Syntax
The jQuery syntax is tailor made for selecting HTML
elements and performing some action on the
element(s)
Basic syntax is: $(selector).action()
A $ sign to define/access jQuery
A (selector) to "query (or find)" HTML elements
A jQuery action() to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$("#test").hide() - hides the element with id="test".
55
The Document Ready Event
All jQuery methods are usually inside a document
ready event:
$(document).ready(function(){
//jQuery methods go here...
});
OR
$(function(){
// jQuery methods go here...
});
This helps to prevent any jQuery code from running
before
the document is finished loading (is ready) 56
jQuery Selectors
jQuery selectors are used to "find" (or select)
HTML elements based on their id, classes,
types ….
It's based on the existing CSS Selectors, and in
addition, it has some own custom selectors.
All selectors in jQuery start with the dollar
sign and parentheses: $()
57
jQuery Selectors Cont’d
The element Selector
selects elements based on the element name.
to select all <p> elements on a page like this:
$("p")
The #id Selector
uses the id attribute of an HTML tag to find the specific element.
to find an element with a specific id, write a hash character, followed
by the id of the HTML element:
$("#test")
The .class Selector
finds elements with a specific class.
to find elements with a specific class, write a period character,
followed by the name of the class:
$(".test") 58
jQuery Selectors Cont’d
• Other jQuery Selectors
$("*"): Selects all elements
$("p.intro"): Selects all <p> elements with class="intro"
$("ul li:first"): Selects the first <li> element of the first <ul>
$("ul li:first-child"): Selects the first <li> element of every <ul>
$("[href ]"): Selects all elements with an href attribute
$("a[target='_blank']"): Selects all <a> elements with a target
attribute value equal to "_blank"
$("a[target!='_blank']"): Selects all <a> elements with a target
attribute value NOT equal to "_blank"
$(":button"): Selects all <button> elements and <input>
elements of type="button"
$("tr:even"): Selects all even <tr> elements
59
jQuery Event Methods
jQuery is tailor-made to respond to events in an HTML
page
jQuery Syntax For Event Methods
To assign a click event to all paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event
fires. You must pass a function to the event:
$("p").click(function(){ Example:
// action goes here!!
$("p").click( function()
});
Using the on() Method {
$("p").on("click", function(){
$(this).hide();
//action goes here
}); }); 60
jQuery Event Example
61
jQuery Effects: Hide & Show
Used to hide and show HTML elements
Syntax:
$(selector).hide(speed,callback);
$(selector).show(speed,callback);
$(selector).toggle(speed,callback);
The optional speed parameter specifies the speed of
the hiding/showing, and can take the following
values: "slow", "fast", or milliseconds.
The optional callback parameter is a function to be
executed after the hide() , show() or toggle() method
completes
62
jQuery Effects: Hide & Show Examples
63
jQuery Fading Methods
With jQuery you can fade an element in and out
of visibility.
jQuery has the following fade methods:
fadeIn(speed,callback) is used to fade in a hidden
element.
fadeOut(speed,callback) is used to fade out a visible
element
fadeToggle(speed,callback) toggles between the
fadeIn() and fadeOut() methods
fadeTo(speed,callback) allows fading to a given
opacity (value between 0 and 1) 64
jQuery Fading Methods Example
65
jQuery Slide Methods
With jQuery you can create a sliding effect on
elements.
jQuery has the following slide methods:
slideDown(speed, callback) is used to slide down
an element
slideUp(speed, callback) is used to slide up an
element
slideToggle()
66
jQuery Slide Methods Example
67
jQuery DOM Manipulation
jQuery offers the following methods for DOM
manipulation:
text() - Sets or returns the text content of
selected elements
html() - Sets or returns the content of
selected elements
(including HTML markup)
val() - Sets or returns the value of form fields
attr() – Sets or returns attribute values
68
jQuery DOM Methods Example
69
jQuery Add Elements
With jQuery, it is easy to add new elements/content.
Four jQuery methods that are used to add new
content:
append() - Inserts content at the end of the selected
elements
prepend() - Inserts content at the beginning of the
selected elements
after() - Inserts content after the selected elements
before() - Inserts content before the selected elements
70
jQuery Add Elements Example
71
jQuery Remove Elements
To remove elements and content, there are mainly two
jQuery methods:
remove() - Removes the selected element (and its
child elements)
also accepts one parameter, which allows you to filter
the elements to be removed.
The parameter can be any of the jQuery selector
syntaxes.
empty() - Removes the child elements from the
selected element
72
jQuery Remove Elements Example
73
jQuery Manipulating CSS
jQuery has several methods for CSS manipulation. We
will look at the following methods:
addClass() - Adds one or more classes to the
selected elements
removeClass() - Removes one or more classes from
the selected elements
toggleClass() - Toggles between adding/removing
classes from the selected elements
css() - Sets or returns one or more style
properties for the selected elements
Syntax: css("propertyname"); &
css("propertyname","value");
74
jQuery Manipulating CSS Examples
75
jQuery Method Chaining
With jQuery, you can chain together actions/methods
Chaining allows us to run multiple jQuery methods
(on the same element) within a single statement
This way, browsers do not have to find the same
element(s) more than once
To chain an action, you simply append the action to
the previous action using a dot
76
77
Reading Assignment
Using Callback functions with text(), val() & attr()
jQuery Animate
jQuery Dimensions
jQuery AJAX
78
79