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

Web Technology II - JavaScript

Uploaded by

Versatile Avi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Web Technology II - JavaScript

Uploaded by

Versatile Avi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 120

WEB TECHNOLOGY II - JavaScript

Computer Science, XII


St. Xavier’s College
CLIENT SIDE SCRIPTING
WITH JAVASCRIPT

Computer Science
Preface to JavaScript

▪ “Any application that can be written in JavaScript,


will eventually be written in JavaScript.”
-Jeff Atwood (creator of Stack Overflow)

▪ One of the most basic languages used in developing


websites, equally web and mobile applications.
Preface to JavaScript
▪ Invented by Brendan Eich in 1995.
▪ Initial intention was to design a universal
programming language that could serve as a
scripting companion to Java.
▪ Was only used to create interactive pages and was
limited only to the web browser.
▪ Became the pioneer of modern web development.
Introduction to JavaScript
▪ A text-based programming language that can be
used on both client and server side.
▪ Both synchronous and asynchronous programming
language.
○ HTML: structure
○ CSS: style
○ Javascript: responsible for interactive elements
that engage the user.
Introduction to JavaScript
▪ A lightweight, scripting language.
▪ Designed to add interactivity to HTML pages.
▪ Usually embedded directly into HTML pages.
▪ An interpreted language.
▪ Everyone can use JavaScript without purchasing a
license.
Features of JavaScript
▪ Weakly typed language.
▪ Object oriented programming language.
▪ Case sensitive language.
▪ Provides good control to the users over the
browsers.
Purpose of JavaScript
▪ Used to create modern web applications for direct
interaction without reloading the page each time.
▪ Commonly used to modify HTML and CSS
dynamically to update user interface.
▪ A powerful tool for developing mobile applications.
▪ Used to develop browser-based games.
Importance of JavaScript
▪ Compatibility with other languages.
▪ Easy to learn.
▪ Responsiveness.
▪ Programming without compilation.
▪ AJAX (Asynchronous JavaScript and XML).
▪ Large library base.
▪ Compatibility with other browsers.
Adding JavaScript in HTML
▪ JavaScript can be added in HTML by 2 ways:
○ Writing the code directly in HTML.
○ Including it as a link to an external file.
▪ <script> tag is used.
Adding JavaScript directly in
HTML.
Adding JavaScript to a Separate
FIle
How to run JavaScript?
▪ Requirements:
○ HTML
○ Any web browser
JavaScript Syntax
▪ Written inside <script> tag.
▪ Recommended to use <script> tag inside <head> tag.
▪ Ignores whitespaces and line breaks.
▪ Semicolons are optional.
▪ Case sensitivity.
JavaScript Comment
▪ There are two types of comments in JavaScript.
○ Single-line Comment (use //)
○ Multi-line Comment (use /* */)
JavaScript Data Types
JavaScript Data Types
Undefined and NULL
▪ Undefined:
○ A data type whose
variable is not
initialized.
▪ Null:
○ Denotes a null
value.
JavaScript Data Types
Arrays & Objects
▪ Arrays are a special
type of objects.
▪ Arrays use index to
access it “elements”.
▪ Objects use names to
access its “members”.
▪ person.firstname
returns John.
JavaScript Data Types
Arrays & Objects Properties
▪ length, sort(), push.
▪ person.length returns
number of elements.
▪ person.sort() sorts the
array.
▪ person.push(“Jenny”)
adds Jenny to the
array.
JavaScript Data Types
Arrays & Objects Usage
▪ JavaScript does not support associative array.
▪ Use objects when you want the elements
names to be string.
▪ Use arrays when you want element names to
be numbers.
JavaScript Data Types
Creating Array with new Array()
▪ JavaScript has a built-in array constructor
new Array().
JavaScript Variables
▪ Ways to declare variables in JavaScript:
○ Using var
○ Using let
○ Using const
○ Using nothing
Difference between var and let

▪ Variables defined with


let cannot be
redeclared.
▪ Variables define with
let have block scope.
Const variable

▪ Variables defined with const cannot be redeclared.


▪ Variables defined with const cannot be reassigned.
▪ Variables defined with const have block scope.
▪ Constant can be arrays and objects as well.
Variable Scopes

▪ JavaScript has 3 types of scope:


○ Block scope
○ Function scope (local scope)
○ Global scope
JavaScript Functions

▪ Defined with the function keyword followed by a


name, followed by parentheses ( ).
▪ Parentheses may include parameter name separated
by commas. (parameter1, parameter2,...)
▪ The code to be executed by the function is placed
inside curly brackets: {}
JavaScript Functions Syntax
JavaScript Functions Invocation

▪ The code inside the function will execute when it is


invoked (called).
○ When an event occurs (when a user clicks a
button).
○ When it is invoked from JavaScript code.
○ Automatically (self invoked)
JavaScript Function Example
JavaScript Operators
▪ Self Study
○ Logical Operators
○ Arithmetic Operators
○ Comparison Operators
○ Assignment Operators
JavaScript Control Statements

▪ Self Study
○ IF
○ IF ELSE
○ IF ELSE IF
○ SWITCH
JavaScript Loops

▪ Self Study
○ FOR
○ WHILE
○ DO-WHILE
○ NESTED FOR
JavaScript Input

▪ Input in JavaScript can be taken in following ways:


○ From HTML using <input>, <p> tags etc.
○ From prompt() method.
Taking Input using <input> tag
▪ Use DOM element
document.getElementById(‘id’).value
Taking Input using prompt()
▪ Used to display a prompt box that prompts the user
for the input.
▪ Generally used to take the input from the user
before entering the page.
▪ Syntax: prompt(message, default)
○ Message: It is the text displays to the user.
○ default: An optional parameter. Used to display
the default string value displayed in the textbox.
Taking Input using prompt()
Using parseInt() method
▪ The parseInt method converts its first argument to a
string, parses that string, then returns an integer or
NaN.
▪ Ex:
JavaScript Output

▪ JavaScript can display data in different ways:


○ Writing into an alert box: window.alert()
○ Writing into the browser console: console.log()
○ Writing into HTML output: document.write()
○ Writing into HTML element: innerHTML
JS Output: window.alert()

▪ Use alert box to display output.


▪ Window keyword is optional.
○ Syntax: alert(“string”);
○ Syntax: alert(number);
○ Syntax: alert(variables);
JS Output: console.log()

▪ Use browser console to display the output.


▪ Used for debugging purposes.
▪ Syntax: console.log(“string”);
▪ Syntax: console.log(number);
▪ Syntax: console.log(variables);
JS Output: document.write()

▪ Used to load the HTML from write() method.


▪ Deletes all existing HTML when used on a loaded
document.
▪ Syntax: document.write(“string”);
▪ Syntax: document.write(number);
▪ Syntax: document.write(variables);
JS Output: innerHTML()

▪ Use document.getEelementById(‘id’) method.


▪ innerHTML defines the HTML content.
JavaScript Array

▪ Special variable which can hold more than one


value.
▪ Syntax: const array_name = [item1, item2, …];
▪ Example: const cars = [“Volvo”, “BMW”, “Honda”];
Accessing Array Elements in JS
▪ Use index number to access the array elements.
Changing Array Elements in JS
▪ Use index number to assign the new array element.
Length Property of Array
▪ Returns the number of array elements inside the
array.
JavaScript Array Methods
▪ Converting Arrays to Strings
▪ Popping and Pushing
▪ Array Sorting
Converting Arrays to Strings
▪ toString() method converts an array to a string of
comma separated values.
Popping and Pushing
▪ It is easy to add or remove elements in array.
▪ Pop: Remove an element from an array.
▪ Push: Add an element to an array.
Popping an Element from Array
▪ pop() method removes the last element from an
array.
▪ Returns the value that was popped out.
Popping an Element from Array
Popping an Element from Array
Pushing an Element to Array
▪ push() method adds a new element to an array at
the end.
▪ Returns the new array length.
Pushing an Element to Array
Pushing an Element to Array
Array Sorting

▪ sort() method sorts an array alphabetically.


▪ reverse() method reverses the elements in an array.
Array Sorting
Numeric Array Sorting

▪ By default, sort() method sorts values as strings.


▪ “25” will be greater than “100”.
▪ Use compare function to fix this problem.
Numeric Array Sorting
The Compare Function

▪ If the result is negative, a is sorted before b.


▪ If the result is positive, b is sorted before a.
▪ If the result is zero, no changes are done.
Highest/Lowest Array Value

▪ No built-in functions for finding the max or min


value in an array.
▪ After sorting the array, the max and min values can
be obtained with the help of index.
Highest/Lowest Array Value
JS Array Const

▪ Arrays are not constant.


▪ Const keyword does not define a constant array.
▪ It defines a constant reference to an array.
▪ Const keyword also uses block scope.
JS Objects

▪ One of the data types in JavaScript.


▪ A standalone entity with properties and type.
▪ JS is not a pure Object Oriented programming
language, but supports some features like objects
and methods.
Real World Example of Objects

Object Properties Methods

Car.name = Audi car.start()

Car.model = 121A car.drive()

Car.weight = 1000 kg car.brake()

Car.color = Green car.turnRight()


Real World Example of Objects

▪ In real life, a car is an object.


▪ All cars have same properties but the property
values differ from car to car.
▪ All cars have same methods, but the methods are
performed at different times.
JS Object Definition

▪ Define (create) JS object with object literals.


▪ Ex:
Accessing Object Properties

▪ Properties of Object can be accessed in two ways:


▪ Syntax:
○ objectName.propertyName
○ objectName[“propertyName”]
▪ Ex: console.log(car.name)
▪ Ex: car[“weight”]
JS Object Methods
▪ Objects can also have methods.
▪ Actions that can be performed on objects.
▪ Stored in properties as function.
▪ To access object methods:
○ Syntax:
■ objectName.methodName()
JS Object Methods

▪ To access: person.fullName();
▪ this refers to owner of the function.
Various JavaScript Objects
▪ Strings objects
▪ Dates objects
▪ Maths objects
JS Strings

▪ Strings are used for storing and manipulating text.


▪ Both double and single quotes can be used.
JS Strings Methods

▪ String length
▪ String toUpperCase()
▪ String toLowerCase()
▪ String concat()
JS Strings Methods
JS Dates

▪ Used to work with dates in JavaScript.


▪ Syntax:
○ new Date(year,month,day,hours,minutes,seconds,ms);
JS Dates
JS Math

▪ Math methods and properties can be used without


creating a Math object first.
JS Math
Math.PI Returns value of PI.
Math.round(x) Returns nearest integer.
Math.floor(x) Returns the value of x rounded down to its nearest integer.
Math.trunc(x) Returns the integer part of x.
Math.pow(x,y) Returns the value of x to the power y.
Math.sqrt(x) Returns the square root of x.
Math.abs(x) Returns the absolute (positive) value of x.
Math.min(), Used to find the lowest and highest value in a list of
Math.max() arguments.

Math.random() Returns random number between 0 and 1.


JS Math Max and Min
HTML DOM
▪ When a web page
is loaded, the
browser creates a
Document Object
Model of the page.
▪ HTML DOM is
constructed as a
tree of Objects:
DOM (Document Object Model)
/ HTML DOM
▪ Programming interface for web documents.
▪ Represents the page so that programs can change
the document structure, style and content.
▪ Represents the document as nodes and objects
through which programming languages can interact
with the page.
DOM (W3 Consortium)

▪ According to W3C (World Wide Web Consortium):


○ DOM is a platform and language-neutral interface.
○ Allows programs and scripts to dynamically access
and update the content, structure and style of a
document.
DOM Manipulation with JS
▪ JS can manipulate DOM through object model:
○ JS can change all the HTML elements and
attributes in the page.
○ JS can change all the CSS styles in the page.
○ JS can add new HTML elements and attributes.
○ JS can react to all existing HTML events in the page.
○ JS can create new HTML events in the page.
DOM Methods and Properties
▪ Methods:
○ Actions you can perform on HTML elements.
○ Like add or delete an HTML element.
○ Ex: getElementById(“id”)
▪ Properties:
○ Values of HTML elements that you can get, set or
change.
○ Like changing the content of an HTML element.
○ Ex: innerHTML
DOM Methods and Properties
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.
document.querySelectorAll(tagname.class) Find all elements with specified
class name.
Changing HTML Elements
Property Description
element.innerHTML = new html content Change inner HTML of an element.
element.attribute = new value Change attribute value of an HTML
element.

element.style.property = new style Change style of an HTML element.


Method Description
element.setAttribute(attribute,value) Change attribute value of an HTML
element.
Adding & Deleting Elements
Method Description
document.createElement(element) Create an HTML element.
document.removeChild(element) Remove an HTML element.
document.write(text) Write into the HTML output stream.
Changing HTML Content
Changing Value of an Attribute
Changing HTML Style
Exercise
▪ Change the content of h1 tag to “Welcome to our
Courses”.
▪ Change text color of h2 tag to red.
▪ Set the value of name field to “Kiran”.
▪ Change the type attribute of email field to “email”.
▪ Get the value of phone field.
▪ Change the font and size of submit button text.
HTML Events
▪ Change in state of an object is known as an Event.
▪ Various events represents some activity that is
performed by the user or the browser.
▪ Ex:
○ When a user clicks the mouse
○ When a web page or image has loaded
○ When a key is pressed
○ When the mouse moves over an element
Event Handling in JS
▪ The process of reacting over the events is called
Event Handling.
▪ JS handles the HTML events via Event Handlers.
▪ Example of Event Handlers implementation:
○ A notification pops up on the page when it is
reloaded.
○ The background color changes on a mouse click.
Event Handling in JS
▪ Event Handlers can be directly used from HTML tags.
Event Handling in JS
▪ Event Handlers can be linked to a function.
Event Handling in JS
▪ Event
Handlers
can be
linked
with DOM
reference
as well.
Common JS Events
▪ Mouse Events:
Event Description
onclick Occurs when user clicks on an element.
onmousedown Occurs when user presses a mouse button over
an element.

onmousemove Occurs when pointer is moving while it is over an


element.

onmouseout Occurs when a user moves mouse pointer out of


an element.
Common JS Events
▪ Mouse Events:
Event Description
onmouseover Occurs when the pointer is moved onto an
element.

onmouseup Occurs when a user releases a mouse button


over an element.

onmouseenter Occurs when pointer is moved onto an element.


onmouseleave Occurs when pointer is moved out of an element.
Mouse Event Handling in JS
▪ Change color of
text on mouse
over event.
Common JS Events
▪ Keyboard Events:
Event Description
onkeydown Occurs when the user is pressing a key.
onkeyup Occurs when the user releases a key.
onkeypress Occurs when the user presses a key.
Keyboard Event Handling in JS
▪ Get input value
from field on
every key press.
Common JS Events
▪ Image Object Events:
Event Description
onload Occurs when an image is loaded and displayed
into the browser window.

onerror Occurs when an error is encountered during


loading process of an image.

onabort Occurs when the user interrupt or cancels loading


of an image
Image Object Events JS
▪ Image Object Events:
Common JS Events
▪ Text Fields Object Events:
Event Description
onfocus Occurs when text field receives the focus.
onblur Occurs when user loses the focus from the text
field.

onselect Occurs when a user selects text within a text field.


Common JS Events
▪ Form Object Events:
Event Description
onsubmit Occurs when form is submitted by the user.
onreset Occurs when the user clicks reset button of form.
onclick Occurs when submit or reset button is clicked.
Form Event Handling in JS
Form/Data Validation
▪ Data validation is the process of ensuring that user
input is clean, correct and useful.
▪ Main purpose of data validation is to ensure correct
user input.
▪ Validation can be deployed in different ways:
○ Server side validation: performed by web server
○ Client side validation: performed by browser.
Form/Data Validation Tasks

▪ Has the user filled in all required fields?


▪ Has the user entered a valid email address?
▪ Has the user entered text in a numeric field?
▪ Has the user entered phone number of 12 digits?
Form/Data Validation Process

▪ Basic Validation: makes sure all fields are filled in.


▪ Data Validation: makes sure the entered data is in
correct form and value. Requires appropriate logic to
test correctness of data.
Form Validation in JS
(Sample Form)
Basic Validation in JS
▪ Makes sure the input field is filled in.
Data Validation in JS
▪ Makes sure phone value is in number format.
Data Validation in JS
▪ Makes sure length and value of password matches.
jQuery
▪ A lightweight, feature-rich JavaScript library.
▪ Allows you to “write less, do more”.
▪ jQuery wraps common tasks that require many lines
of code into methods that can be called with a single
line of code.
▪ Output from jQuery renders correctly in any modern
browser.
jQuery
Features of jQuery
▪ Simple and easy.
▪ Lightweight library.
▪ Predefined css() method to manipulate styles.
▪ Easy html manipulation.
▪ Cross browser support.
▪ Easy event handling.
▪ AJAX Support
▪ Built-in Animation
jQuery Code Sample
THE END

Computer Science

You might also like