Unit II - Java Script, DOM JQuery

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

Web Technology

Unit- II

Topic:
Java Script, DOM, JQuery, AngularJS
JavaScript:
● Introduction to JavaScript,
● JavaScript in perspective,
● basic syntax,
● variables and data types,
● statements,
● operators,
● literals,
● functions,
● objects,
● arrays,
● built in objects,
● JavaScript debuggers
JS- Java Script

Java Script

Client Side Dynamic front-end


Scripting scripting
Language language
JavaScript Advantages

• Changing an image • Performing complex


Implementing form
on moving mouse over calculations
validation
it

• Sections of a page
• Content loading and
• React to user actions, appearing and
changing dynamically
disappearing
What Can JavaScript Do?

• Can validate form • Can read and write


data HTML elements

• Can access / modify


Can handle events
browser cookies
What Can JavaScript can’t Do?

• Can not do database related • Can not close a window


operation that it hasn't opened.

Cannot Read From or Write • Cannot Protect Your


to Files in the Client. Page Source or Images
JavaScript - Placement in HTML File

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

Script in Script in External file and then include


<head> and <body> section link in HTML file head section
Syntax of Javascript

Write JavaScript code inside HTML


Head Tag, Body Tag or External File

Use <Script> tag inside Head,body tag

Example:
<script >
JavaScript code
</script>
Java Script Example- 1
Print Hello Message

<html>
<body>
<script>
Script Code in HTML document.write("Hello World")
file in Body Tag
</script>
</body>
</html>
Java Script Example- 2
Print Hello Message

<html>
<head>
<script>
Script Code in HTML document.write("Hello World")
file in Head Tag
</script>
</head>
</html>
Java Script Example- 3
Print Hello Message

<html>
<head>
<script> Print Message using
alert
alert("Hello World")
</script>
</head>
</html>
Java Script Example- 4
Print Hello Message

<html>
<head>
<script>
function sayHello()
{ alert("Hello World") } Print Message after
clicking button
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Javascript Variables
JS- Java Script Variables

4 Ways to Declare Java Script Variables

1. Using Var 2. Using Let 3. Using Const

4. Using Nothing
JS- Java Script Variables

Always declare JavaScript variables with var,let, or const.


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
JS- Java Script Variables

Example
Example ByBy using
using letVar Example By using Const
letvar
x =x5;
= 5; const x = 5;
letvar
y =y6;
= 6; const y = 6;
letvar
z =zx=+xy;+ y; let z = x + y;

Example By using nothing


x = 5;
y = 6;
z = x + y;
Variable naming conventions in JavaScript

● You should not use any of the JavaScript reserved keywords as a variable name.
These keywords are mentioned in the next section. For example, break or boolean
variable names are not valid.
● JavaScript variable names should not start with a numeral (0-9). They must begin
with a letter or an underscore character. For example, 123test is an invalid variable
name but _123test is a valid one.
● JavaScript variable names are case-sensitive. For example, Name and name are
two different variables.
Javascript Data Types
Java Script Data Types

Java Script Data


Types

Primitive Non-Primitive
Java Script Data Types
Primitive

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all


Java Script Data Types
Non- Primitive

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression


Javascript Statements
Javascript Statements

The programming instructions written in a program in a programming language are known as


statements.
Order of execution of Statements is the same as they are written.
1. Semicolons:
· Semicolons separate JavaScript statements.
· Semicolon marks the end of a statement in javascript.
Java Script Statements

2. Code Blocks:
· JavaScript statements can be grouped together inside curly brackets. { }
· Such groups are known as code blocks. The purpose of grouping is to define statements to be executed together.
3. White Space:
· Javascript ignores multiple white spaces.
4. Line Length and Line Breaks:
· Javascript code preferred line length by most programmers is upto 80 characters.
· The best place to break a code line in Javascript, if it doesn’t fits, is after an operator.
JavaScript Statements
5. Keywords:
· Keywords are reserved words and cannot be used as variable name.
· A Javascript keyword tells about what kind of operation it will perform.
· Some commonly used keywords are:
1. break: This is used to terminate a loop or switch.
2. continue: This is used to skip a particular iteration in a loop and move to next iteration.
3. do…. while: In this the statements written within do block are executed till the condition in while is true.
4. for: It helps in executing a block of statements till the condition is true.
5. function: This keyword is used to declare a function.
6. return: This keyword is used to exit a function.
7. Var, Let, Const: This keyword is used to declare a variable.
8. switch: This helps in executing a block of codes depending on different
Javascript Operators
JavaScript Operators:Arithmetic Operators
JavaScript Operators:Assignment Operators
JavaScript Operators:Comparison Operators
JavaScript Operators:Logical Operators
Javascript Literals
JavaScript- Literals

● JavaScript Literals are the fixed value that cannot be changed,


● you do not need to specify any type of keyword to write literals.
● Literals are often used to initialize variables in programming, names of
variables are string literals.
JavaScript- Literals

JavaScript supports various types of literals which are listed below:


● Numeric(Integer) Literal
● Floating-Point Literal
● Boolean Literal
● String Literal
● Array Literal
● Regular Expression Literal
● Object Literal
JavaScript- Numeric(Integer) Literal

● It can be expressed in the decimal(base 10), hexadecimal(base 16) or octal(base 8) format.


● Decimal numeric literals consist of a sequence of digits (0-9) without a leading 0(zero).
● Hexadecimal numeric literals include digits(0-9), letters (a-f) or (A-F).
● Octal numeric literals include digits (0-7). A leading 0(zero) in a numeric literal indicates octal
format.
120 // decimal literal
021434 // octal literal
0x4567 // hexadecimal literal
JavaScript- Floating Literal

● It contains a decimal point(.)


● A fraction is a floating-point literal
● It may contain an Exponent.
6.99689 // floating-point literal

-167.39894 // negative floating-point literal


JavaScript- Boolean Literal

Boolean literal supports two values only either true or false.

true // Boolean literal

false // Boolean literal


JavaScript- String Literal

A string literal is a combination of zero or more characters enclosed within a single(') or double
quotation marks (").

"Study" // String literal

'tonight' // String literal


JavaScript- Array Literal

● An array literal is a list of zero or more expressions representing array elements that
are enclosed in a square bracket([]).
● Whenever you create an array using an array literal, it is initialized with the elements
specified in the square bracket.

var emp = ["aman","anu","charita"]; // Array literal


JavaScript- Regular Expression Literal

● Regular Expression is a pattern, used to match a character or string in some text.


● It is created by enclosing the regular expression string between forward slashes.

var r1 = /ab+c/; // Regular Expression literal


var r2 = new RegExp("abc"); // Regular Expression literal
JavaScript- Object Literal

● JavaScript Object Literal


● It is a collection of key-value pairs enclosed in curly braces({}).
● The key-value pair is separated by a comma.

var games = {cricket : 11, chess : 2, carom : 4} // Object literal


Javascript Functions
Java Script Functions

❏ Anonymous Function

❏ Named Function

❏ Function with return statement


Anonymous Function

<script>
var showMessage = function (){
alert("Hello World!");
};
showMessage();
</script>
Named Function without argument

function SayHello() {
alert("Hello ");
}

SayHello();
Named Function with argument

function SayHello(firstName) {
alert("Hello " + firstName);
}

SayHello("Bhavana");
Function with return statement

function sum(val1, val2) {


return val1 + val2;
};

var result = sum(10,20);


Javascript Arrays
JavaScript -Arrays

❏ How to Create array in Javascript

❏ How to access Values of Arrays in Javascript

❏ Arrays Properties and Methods


Java Script -Arrays
How to Create array in Javascript

● Method 1:
○ var cars = ["Saab", "Volvo", "BMW"];
● Method 2:
○ var cars = new Array("Saab", "Volvo", "BMW");
● Method 3:
○ cars[0] = “Saab”
○ cars[1]= “Volvo”
○ cars[2]= “BMW”
Java Script -Arrays
How to access Values of Arrays in Javascript

● Method 1:- To Access only one value


○ var name = cars[0];
● Method 2: To Access only one value with showing it in HTML Page
○ document.getElementById("t1").value = cars[0];
● Method 3: To Access full Array
○ document.getElementById("t1").value= cars;
Java Script -Arrays
Array Properties & Methods

● Length
● Reverse
● Sort
● Push
● Pop
● forEach
Javascript Objects
Java Script -Objects

❏How to Create object in Javascript

❏How to read Properties of an Object in Javascript


Java Script -Objects
How to Create object in Javascript

● Objects are variables too. But objects can contain many values.
● The values are written as name : value pairs
● Method -1
○ var person = {name:"Bhavana", age:40};
● Method -2
○ var person = new Object();
○ person.name = "Bhavana";
○ person.age = 40;
Java Script -Objects
How to Read/Access Properties of an Object in Javascript

➢ Method- 1 Syntax ➢ Method 2


○ objectName.property ○ objectName["property"]
➢ Method- 1 Example ➢ Method- 2 Example
○ person.age ○ person["age"]
Javascript Build in Objects
Build in objects (Ref-https://www.ques10.com/p/29073/explain-built-in-objects-of-javascript/)
Array Object

Properties of the Array object


Length - Returns the number of elements in the array.

Methods of the Array object


reverse() - Reverses the array elements
concat() - Joins two or more arrays
sort() - Sort the elements of an array
push() - Appends one or more elements at the end of an array
pop() - Removes and returns the last element
Date Object

Methods of Date object


Date() - Returns today's date and time
getDate() - Returns the day of the month for the specified date
getDay() - Returns the day of the week for the specified date
getFullYear() - Returns the year of the specified date
getHours() - Returns the hour in the specified date according to local time.
getMilliseconds() - Returns the milliseconds in the specified date according to local time.
Maths Object

Properties of Math object Methods of Math object


PI - The value of Pi max(a,b) - Returns largest of a and b
E - The base of natural logarithm e min(a,b) - Returns least of a and b
LN2 - Natural logarithm of 2 round(a) - Returns nearest integer
LN10 - Natural logarithm of 10 exp(a) - exponential
LOG2E - Base 2 logarithm of e pow(a,b) - Power
LOG10E - Base 10 logarithm of e abs(a) - Returns absolute value of a

SQRT2 - Square root of 2 random() - Returns a pseudo random number between 0 and 1
sqrt(a) - Returns square root of a
Javascript Debugger
Javascript Debugger

● All modern browsers have a built-in JavaScript debugger.

● Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

● With a debugger, you can also set breakpoints (places where code execution can be stopped), and
examine variables while the code is executing.

● You activate debugging in your browser with the F12 key, and select "Console" in the debugger
menu.

Example- Click Here


Javascript Debugger

● The debugger keyword stops the execution of JavaScript, and calls (if available) the debugging
function.

● This has the same function as setting a breakpoint in the debugger.

● If no debugging is available, the debugger statement has no effect.

● With the debugger turned on, this code will stop executing before it executes the third line.

Example- Click Here


Advantages of JavaScript

❏ Speed: Client-side JavaScript is very fast because it can be run immediately


within the client-side browser.
❏ Simplicity: JavaScript is relatively simple to learn and implement.
❏ Popularity: JavaScript is used everywhere on the web.
❏ Interoperability: JavaScript plays nicely with other languages and can be used
in a huge variety of applications.
❏ Server Load: Being client-side reduces the demand on the website server.
❏ Rich Interface: Gives the ability to create rich interfaces.
Disadvantages of JavaScript

❏ Client-Side Security: Because the code executes on the users’ computer, in some
cases it can be exploited for malicious purposes. This is one reason some people
choose to disable Javascript.
❏ Browser Support: JavaScript is sometimes interpreted differently by different
browsers. This makes it somewhat difficult to write cross-browser code
DOM
DOCUMENT OBJECT MODELING
DOM-

● DOM history and levels,


● intrinsic event handling,
● modifying element style,
● the document tree,
● DOM event handling
DOM- Introduction

❏ JavaScript can access all the elements in a webpage making use of


Document Object Model (DOM).
❏ The web browser creates a DOM of the webpage when the page is
loaded.
❏ The DOM defines a standard for accessing documents
❏ The DOM model is created as a tree of objects
DOM- Uses

With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
1. JavaScript can change all the HTML elements in the page
2. JavaScript can change all the HTML attributes in the page
3. JavaScript can change all the CSS styles in the page
4. JavaScript can remove existing HTML elements and attributes
5. JavaScript can add new HTML elements and attributes
DOM- Tree

<html>
<head>
<title> My Text </title>
</head>
<body>
<h1> My Header </h1>
<p> My Paragraph </p>
</body>
</html>
DOM Levels

DOM Levels

Level 0 Level 1 Level 2 Level 3

Core2, View, CORE3, LOAD and SAVE,


Low Level Core,
Event, Style, VALIDATION, EVENTS,
Interface HTML Traversal, Range and XPATH.
DOM- Properties & Methods

Methods Description

getElementById(id) Find an element by element id

getElementsByTagName(name) Find an element by Tag Name

getElementsByClassName(name) Find an element by Class Name

getElementsByName(name) Find an element by element name

write() Writes new text to a document


DOM- Properties & Methods

Methods Example

.innerHTML document.getElementById(“demo”).innerHTML

..Value document.getElementById(“t1”).Value
DOM- Examples: getElementById

<html>
<head><script>
function f1() {
var a= document.getElementById("t1").value;
alert(a); }
</script></head>
<body>
<input type="text" id="t1" >
<input type=button value="click" onclick="f1()">
</body>
</html>
DOM- Examples: getElementsByTagName

<html>
<head><script>
function f1() {

document.getElementsByTagName("p")[0].innerHTML="HTML"; }
</script></head>
<body>
<p> Hello</p>
<p > How Are You </p>
<input type=button value="click" onclick="f1()">
</body>
</html>
DOM- Examples: getElementsByClassName
<html>
<head><script>
function f1() {

document.getElementsByClassName("a1")[1].innerHTML="HTML"; }
</script></head>
<body>
<p> Hello</p>
<p class= “a1”> How Are You </p>
<h1 class= “a1”>Good Day </h1>
<input type=button value="click" onclick="f1()">
</body>
</html>
DOM- Examples: To Count Total elements

<script>
function f1() {
alert(document.getElementsByTagName("p").length); }
</script><body>
<p> Hello</p>
<p class= “a1”> How Are You </p>
<h1 class= “a1”>Good Day </h1>
<input type=button value="click" onclick="f1()">
</body>
DOM- Examples: To change CSS Property
<html>
<head><script>
function f1() {
document.getElementsByClassName("a1")[1].style.color="red"; }
</script></head>
<body>
<p> Hello</p>
<p class= “a1”> How Are You </p>
<h1 class= “a1”>Good Day </h1>
<input type=button value="click" onclick="f1()">
</body>
</html>
DOM- Examples:
To Disable/Enable element

<script>
function f1() {
document.getElementsById("t1").disabled= true; }
</script>
<body>
<input type="text" id="t1" >
<input type=button value="click" onclick="f1()">
</body>
JQUERY
JQuery

jQuery is a JavaScript
jQuery is easy to learn.
Library.

JQuery

jQuery greatly simplifies


jQuery is lightweight.
JavaScript programming.
JQuery

The jQuery library contains the following features:


❏ HTML/DOM manipulation
❏ CSS manipulation
❏ HTML event methods
❏ Effects and animations
❏ AJAX
❏ Utilities
JQuery

Many of the biggest companies on the Web use jQuery,


such as:
Microsoft

Google
Netflix

IBM
Adding jQuery to Your Web Pages

Way
Download the jQuery library from jQuery.com
1

Way
Include jQuery from a CDN, like Google
2
jQuery CDN

<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
jQuery Syntax

$(selector).action()

$ sign to A (selector) to A jQuery action()


define/access find HTML to be performed
jQuery elements on the element
jQuery Examples

$(this).hide() hides the current element

$("p").hide() hides all elements.

$(".test").hide() hides all elements with class="test"

$("#test").hide() hides the element with id="test"


jQuery Example: To hide Paragraph

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
jQuery Example: To change CSS Property
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).css("background-color","Red");
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
jQuery Example: To append/Add element
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).append("Hello");
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
jQuery Example: To remove element
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).remove();
});
});
</script> </head>
<body>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
</body>
Web Technology
Unit- II

Topic:
AngularJS-
AngularJS

• AngularJS is a JavaScript framework.


• It can be added to an HTML page with a <script> tag.
• AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

• Syntax
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"> </script>
AngularJS

AngularJS Extends HTML

• AngularJS extends HTML with ng-directives.


• The ng-app directive defines an AngularJS application.
• The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.
• The ng-bind directive binds application data to the HTML view.
AngularJS- MVC Architecture

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web
applications.
• A Model View Controller pattern is made up of the following three parts −

1. Model − It is the lowest level of the pattern responsible for maintaining data.
2. View − It is responsible for displaying all or a portion of the data to the user.
3. Controller − It is a software Code that controls the interactions between the Model and View.
Steps to create AngularJS

• Step 1 − Load framework- using <Script> tag.


• <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script>
• Step 2 − Define AngularJS Application using ng-app directive
• <div ng-app = ""> ... </div>
• Step 3 − Define a model name using ng-model directive
• <p>Enter your Name: <input type = "text" ng-model = "name"></p>
• Step 4 − Bind the value of above model defined using ng-bind directive.
• <p>Hello <span ng-bind = "name"></span>!</p>
AngularJS - Directives

1. ng-app − This directive starts an AngularJS Application. It is also used to load various AngularJS
modules in AngularJS Application.
<div ng-app = ""> ... </div>
2. ng-init − This directive initializes application data. It is used to put values to the variables to be
used in the application.
<div ng-app="" ng-init="firstName='John'">
AngularJS - Directives

3. ng-model − This directive binds the values of AngularJS application data to HTML input controls.
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
4. ng-repeat − This directive repeats html elements for each item in a collection.
<ol>
<li ng-repeat = "country in countries"> {{ country.name}} </li>
</ol>
AngularJS Example

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"> </script>
<body>
<div ng-app="">
Name: <input type="text" ng-model="name">
<p ng-bind="name"> </p>
</div>
</body>
</html>
AngularJS Example Explained

Example explained:
• AngularJS starts automatically when the web page has loaded.
• The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.
• The ng-model directive binds the value of the input field to the application variable name.
• The ng-bind directive binds the innerHTML of the <p> element to the application variable name.
AngularJS Expression

Expressions are used to bind application data to html.


Expressions are written inside double braces like
• {{ expression}}.
Using numbers
• <p>Expense on Books : {{cost * quantity}} Rs</p>
Using strings
• <p>Hello {{fname+ “ “ +lname }}</p>
Using object
• <p>Roll No: {{student.rollno}}</p>
Using array
• <p>Marks(Math): {{marks[3]}}</p>
AngularJS Expressions -Example

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<body>
OutPut
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
AngularJS - Controllers

AngularJS application mainly relies on controllers to control the flow of data in the application.
• A controller is defined using ng-controller directive.
• Each controller accepts $scope as a parameter which refers to the application/module that
controller is to control.
• <div ng-app="myApp" ng-controller="myCtrl">
AngularJS Controllers- Example
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy