Chapter 3 Web Technology II Javascript
Chapter 3 Web Technology II Javascript
Chapter 3
INTRODUCTION
• Web Technology refers to the various tools and techniques that are utilized in
the process of communication between different types of devices over the
internet.
• A web browser is used to access web pages. Web browsers can be defined
as programs that display text, data, pictures, animation, and video on the
Internet.
• The three core languages that make up the World Wide Web are HTML, CSS,
and JavaScript. In the IT world, the internet is an essential platform, whether
it`s for developing or for consumer use. When developing a website, typically
three main languages come into play. These languages are JavaScript, CSS,
and HTML.
CLIENT SIDE SCRIPTING
• Client-side scripting languages create the scripts that run on the client side
(i.e. your browser). These are sent from the server by server-side scripts. Some
good examples are JavaScript, jQuery, CSS etc.
• Works at the front end and script are visible among the users.
• Does not need interaction with the server for processing.
• HTML, CSS, JavaScript, etc. languages involved.
• Can reduce the load to the server.
• Insecure
SERVER SIDE SCRIPTING
• Server-side scripting is a method of designing websites so that the process or
user request is run on the originating server. Server-side scripts provide an
interface to the user and limit access to proprietary data and help keep
control of the script source code.
• Works in the back end which could not be visible at the client end.
• Requires server interaction for processing.
• PHP, ASP.net, Ruby on Rails, ColdFusion, Python, etcetera. Languages
involved.
• Could effectively customize the web pages and provide dynamic websites.
• Relatively secure.
CLIENT SIDE SCRIPTING VS SERVER
SIDE SCIPTING
Assignment : Write the difference between client side scripting and server side scripting.
INTERNET TECHNOLOGY
• Internet is a global communication system that links together thousands of
individual networks. It allows exchange of information between two or more
computers on a network. Thus internet helps in transfer of messages through
mail, chat, video & audio conference, etc.
• Internet Technologies is a technical field that covers the necessary skills to
develop applications on the Internet or Internet based systems, harnessing e-
commerce, cloud, mobile, and Web based technologies.
INTRODUCTION TO JAVASCRIPT
• JavaScript is a cross-platform, object-oriented scripting language used to
make webpages interactive (e.g., having complex animations, clickable
buttons, popup menus, etc.). There are also more advanced server side
versions of JavaScript such as Node.
• Features
• JavaScript is a light weight, interpreted programming languaae.
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform
INTRODUCTION TO JAVASCRIPT
• Advantages
• Java script has less server interaction.
• It provide immediate feedback to the visitors.
• It provides the increased interactivity.
• You can use JavaScript to give rich interface to your visitors.
• Disadvantages
• Client-side JavaScript does not allow the reading or writing of files. This has kept
for security reasons.
• JavaScript cannot be used for networking applications because there is no such
support available.
• JavaScript doesn’t have any multi-threading or multiprocessor capabilities.
INTRODUCTION TO JAVASCRIPT
• Uses
• Client side validation.
• Dynamic drop down menus.
• Displaying date and time.
• Displaying pop-up windows and dialog boxes.
• Displaying clock.
JAVA SCRIPT FUNDAMENTAL
Note: We can declare multiple at one line using comma (,) operator.
example: var name=“Ram Sita”, age=13, isMarried=false;
Example:
<script>
// using var keyword.
var name = "Ram";
var age = "18";
document.write(name + " is " + age + "year old." + "<br>");
//using let keyword
if (true) {
let address = "butwal";
document.write("address is " + address + "<br>");
}
document.write("address is" + address + "<br>"); //show error address is not defined
//using const keyword
const phoneNo = "9898475869";
document.write("phoneNo is" + phoneNo);
</script>
JAVASCRIPT VARIABLE NAMES
While naming your variables in JavaScript, keep the following rules in mind.
1. You should not use any of the JavaScript keywords as a variable name.
2. JavaScript variable names should not start with a numbers (0-9). For e.g. :
1address is invalid.
4. JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.
GENERATING OUTPUT IN JAVA SCRIPT
a) Writing Output to Browser Console
We can easily output a message or write data to the browser console using the
console.log() method. It is very powerful method for generating detailed output.
For example:
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
B) DISPLAYING OUTPUT IN ALERT
DIALOG BOXES
• We can also use alert dialog boxes to display the message or output data to the user.
An alert dialog box is created using the window.alert() method.
• You can skip the window keyword.
• For example:
Example with out window keyword.
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h1>My First Web Page</h1>
<h1>My First Web Page</h1>
<p>My first paragraph.</p> <p>My first paragraph.</p>
<script>
window.alert(5 + 6); <script>
</script> alert(5 + 6);
</script>
</body>
</html> </body>
C) OUTPUT TO THE BROWSER WINDOW
• We can use the document.write() method to write the content to the
current document only while that document is being parsed.
• For example:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<button type="button" onclick="document.write(5 + 6)">Try it</button>
</body>
</html>
D) INSERTING OUTPUT
INSIDE AN HTML ELEMENT
• We can also write or insert output inside an HTML element using the element’s innerHTML
property.
• However, before writing the output first we need to select the element using a method such
as getElementById().
• For example:
<!DOCTYPE html>
<html>
<body>
<h2>The innerHTML Property</h2>
<p id="demo" onclick="myFunction()">Click me to change my HTML content
(innerHTML).</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "I have changed!";
}
</script>
</body>
</html>
JAVA SCRIPT DATA TYPES
• Data types basically specify what kind of data can be stored and
manipulated within a program.
• There are two types of data types in Java Script.
Primitive Data Type
Non-Primitive Data Type
PRIMITIVE DATA TYPES
• Primitive data types can hold only one value at a time.
Example
let text1 = "John";
let text2 = "Doe";
let text3 = text1 + " " + text2;
The result of text3 will be:
John Doe
JAVASCRIPT LOGICAL OPERATORS
Operator Description
&& logical and
|| logical or
! logical not
JAVASCRIPT 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
?: ternary operator (conditional operator)
JAVASCRIPT BITWISE OPERATORS
• Bit operators work on 32 bits numbers.
• Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.
• The examples above uses 4 bits unsigned examples. But JavaScript uses 32-
bit signed numbers.
Operator Description Example Same as Result Decimal
• if...else statement
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
IF...ELSE STATEMENT
• The 'if...else' statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
Syntax:
if (expression) {
Statement(s) to be executed if expression is true
} else {
Statement(s) to be executed if expression is false
}
EXAMPLE
<html>
Output:
<body> Does not qualify for driving.
<script>
var age = 15;
if (age > 18) {
document.write("<b>Qualifies for driving</b>");
} else {
document.write("<b>Does not qualify for driving</b>");
}
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
IF...ELSE IF... STATEMENT
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax:
The syntax of an if-else-if statement is as follows −
if (expression 1) {
Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
Statement(s) to be executed if expression 3 is true
} else {
Statement(s) to be executed if no expression is true
}
<html>
<body>
<script>
var book = "maths"; EXAMPLE
if (book == "history") {
document.write("<b>History Book</b>");
Output:
} else if (book == "maths") {
Maths Book
document.write("<b>Maths Book</b>");
} else if (book == "economics") { Set the variable to different value and
document.write("<b>Economics Book</b>"); then try...
} else {
document.write("<b>Unknown Book</b>");
}
</script>
<p>Set the variable to different value and then
try...</p>
</body>
<html>
SWITCH CASE
• The basic syntax of the switch statement is to give an expression to evaluate and
several different statements to execute based on the value of the expression. The
interpreter checks each case against the value of the expression until a match is
found. If nothing matches, a default condition will be used.
• Syntax:
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Example:
<script>
var grade='A';
document.write("Entering switch block<br/>");
switch (grade) {
case 'A': document.write("Good job<br/>");
break;
case 'B': document.write("Pretty good<br/>");
break;
case 'C': document.write("Passed<br/>");
break;
case 'D': document.write("Not so good<br/>");
break;
case 'F': document.write("Failed<br/>");
break;
default: document.write("Unknown grade<br/>")
}
document.write("Exiting switch block");
</script>
LOOPING STATEMENTS
• The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.
• for loop
• for-in loop
• for-of loop
• while loop
• do-while loop
FOR LOOP
• The for loop is the most compact form of looping and 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 the given condition is true or not. If
condition is true then code given inside the loop will be executed otherwise
loop will come out.
• The iteration statement where you can increase or decrease your counter.
• Syntax:
Example:
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br/>");
}
Example: This will produce following result which is
similar to while loop −
<script>
var count; Starting Loop
Current Count : 0
document.write("Starting Loop" + "<br/>"); Current Count : 1
for (count = 0; count < 10; count++) { Current Count : 2
Current Count : 3
document.write("Current Count : " + Current Count : 4
count); Current Count : 5
Current Count : 6
document.write("<br/>"); Current Count : 7
} Current Count : 8
Current Count : 9
document.write("Loop stopped!"); Loop stopped!
</script>
FOR IN LOOP
• The JavaScript for in loop is used to iterate the properties of an object. We
will discuss about it later.
• Syntax:
for (key in object) {
// code block to be executed
}
Example: Output:
John
<script> Doe
const person = { fname: "John", lname: 25
"Doe", age: 25 };
for (let x in person) {
document.write(person[x]; +"<br>");
}
</script>
WHILE LOOP
The purpose of a while loop is to execute a statement or code block
repeatedly as long as expression is true. Once expression becomes false, the
loop will be exited.
Syntax:
Initialization;
while (expression){
Statement(s) to be executed if expression is true;
counter parts;
}
Example: This will produce following result −
<script> Starting Loop
var count = 0; Current Count : 0
Current Count : 1
document.write("Starting Loop" + "<br/>"); Current Count : 2
while (count < 10) { Current Count : 3
Current Count : 4
document.write("Current Count : " + Current Count : 5
count + "<br/>"); Current Count : 6
Current Count : 7
count++; Current Count : 8
} Current Count : 9
Loop stopped!
document.write("Loop stopped!");
</script>
DO WHILE LOOP
The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be
executed at least once, even if the condition is false.
Syntax:
initialization;
do {
Statement(s) to be executed;
Counter parts;
} while (expression);
This will produce following result −
• Let’s see the simple example of function in JavaScript that does not has
arguments.
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
64
FUNCTION WITH RETURN VALUE
• We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.
<script>
function getInfo(){
return "hello javascript! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
OBJECT BASED PROGRAMMING WITH
JAVA SCRIPT AND EVENT HANDLING
• Object Based Programming with Java Script
• Properties can hold values of primitive data types and methods are functions.
• An Object can be created within curly braces ({}) with an optimal list of
properties.
CREATING OBJECTS IN JAVASCRIPT
• Here we can attach properties and methods using dot notation. Optionally, we can
also create properties using [] brackets and specifying property name as string.
• Syntax:
var objectName=new Object();
• The example of creating object by object constructor is given below.
BY USING AN OBJECT CONSTRUCTOR
• The example of creating object by object //by dot notation
constructor is given below. document.write(person.firstname + " ");
<script>
document.write(person.lastName + " ");
//creating object constructor using new document.write("Age is" + " " + person.age);
keyword.
document.write("<br>");
var person = new Object();
document.write(person.getFullName());
//Attach properties and methods to person
object document.write("<br>");
person.firstname = "Ram"; //by bracket notation
person["lastName"] = "Sita"; document.write(person["firstname"] + " ");
person.age = 18; document.write(person["lastName"] + " ");
person.getFullName = function () { document.write(person["age"] + "yearold");
return this.firstname + '' + this.lastName; </script>
};
//accessing properties and methods
LOOPING THROUGH OBJECT’S PROPERTIES
• It can iterate through the key value pairs of object using the for in loop. This loop is specially
optimized for iterating over object’s properties.
• Example:
<script>
var person={
name:”Prapti”,
age:12,
gender:”Female”
};
// Iterating over object properties
for(var i in person)
{
document.write(person[i]+””); //Prints: Prapti 12 Female
}
</script>
EVENT HANDLING WITH JAVA SCRIPT
• The change in the state of an object is known as an Event. In html, there are
various events which represents that some activity is performed by the user
or by the browser. When javascript code is included in HTML, js react over
these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event
Handlers.
• For example, when a user clicks over the browser, add js code, which will
execute the task to be performed on the event.
SOME OF THE HTML EVENTS AND
THEIR EVENT HANDLERS ARE:
Mouse events:
Event Event Handler Description
Performed
click onclick When mouse click on an element
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
change onchange When the user modifies or changes the value of a form
element
FOCUS EVENT
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" red";
}
</script>
</body>
Window/Document events
Event Event Handler Description
Performed
load onload When the browser finishes the loading of the
page
unload onunload When the visitor leaves the current webpage,
the browser unloads it
• Example:
var x = document.getElementById("myImg");
CREATE AN IMAGE OBJECT
• You can create an <img> element by using the document.createElement()
method:
• Example:
var x = document.createElement("IMG");
EXAMPLE OF IMAGE OBJECT
<body> var x
<p> Click the button to create an IMG =document.createElement(“IMG”);
element. x.setAttribute(“src”,”rk3.gif”);
</p> x.setAttribute(“width”,”304”);
<button onclick=“myFunction()”> x.setAttribute(“height”,”304”);
Try it x.setAttribute(“alt”,”the image cannot
</button> access now, sorry for inconvenience.”);
<script> documet.body.appendChild(x);
function myFunction() }
{ </script>
</body>
IMAGE OBJECT PROPERTIES
Property Description
align Not supported in HTML5. Use style.cssFloat instead.
Sets or returns the value of the align attribute of an image
alt Sets or returns the value of the alt attribute of an image
border Not supported in HTML5. Use style.border instead.
Sets or returns the value of the border attribute of an
image
width Sets or returns the value of the width attribute of an image
height Sets or returns the value of the height attribute of an
image
naturalHeight Returns the original height of an image
naturalWidth Returns the original width of an image
src Sets or returns the value of the src attribute of an image
FORM OBJECT
• The Form object represents an HTML <form> element.
• You can create a <form> element by using the document.createElement()
method:
• Example:
var x = document.createElement("FORM");
• You can access a <form> element by using getElementById():
• Example:
var x = document.getElementById("myForm");
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validatefo
rm()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
JQUERY
• It is a lightweight, fast, small and feature rich JavaScript Library.
• It makes it much easier to code JavaScript on your website.
• It reduces the development time-consume, easy to add animation and
event handling programs.
• jQuery is a JavaScript framework that makes it easier to program for the
browser.
• jQuery library contains HTML/DOM manipulation, CSS manipulation, effects
and animation etc.
WHY JQUERY?
• Reasons to use jQuery are:
• Easy to understand.
• Easily integrated with other IDE.
• Faster.
• Animation becomes easy.
• SEO friendly.
• Run in all major browsers.
ASSIGNMENT
• Prepare notes and write question answer.