Mod 3
Mod 3
✔Although it contains the word Java, JavaScript and Java are vastly
different programming languages with different uses.
✔Unlike more familiar object oriented languages such as Java, C#, and
Visual Basic, functions in JavaScript are also objects.
✔This means variables can be easily converted from one data type to
another.
✔JavaScript is one such client side scripting language that can operate on
most web browsers.
✔We will next see how a client downloads and executes a JavaScript.
✔The browser can respond more rapidly to user events than a request to a
remote server ever could, which improves the user experience.
✔Client side scripting also gives developers more control over the look and
behaviour of their web pages. Features like drag and drop and sliders can be
added to the web page, which greatly enhances the user interface and
experience of a site.
✔More development time and effort might be required (if the scripts
are not already available through other resources).
✔Before going to the details of JavaScript, we will briefly look at two other
noteworthy client-side approaches to web programming.
✔Adobe Flash is a vector based drawing and animation program, a video file
format, and a software platform that has its own JavaScript-like
programming language called ActionScript.
✔Flash is often used for animated advertisements and online games, and can
also be used to construct web interfaces.
✔Flash objects are in a format called SWF (Shockwave Flash) and are included
within an HTML document via the <object> tag.
✔The SWF file is then downloaded by the browser and then the browser
delegates control to a plug-in to execute the Flash file.
Working of
Adobe Flash
✔Java applets are written using the Java programming language and are
separate objects that are included within an HTML document via the
<applet> tag.
✔This plug-in then passes on the execution of the applet outside the
browser to the Java Runtime Environment (JRE) that is installed on
the client’s machine.
5/27/2022 Mrs. karthiga g 18cs63 12
WHAT IS JAVASCRIPT AND WHAT CAN IT DO?
Working of Java
Applet
✔The layers correspond to the three kinds of code that are used in
building a website: HTML, CSS and JavaScript.
Presentation Layer
✔Focuses on the display of
information.
✔JavaScript can alter the HTML
of a page, which results in a
change, visible to the user.
✔This includes common things
like creating, hiding, and
showing divs, using tabs to
show multiple views etc.
JavaScript Layers
Validation Layer
✔JavaScript can be also used to validate logical aspects of the user’s
experience.
✔This could include, for example, validating a form to make sure the
email entered is valid before sending it along.
✔The main intention of this layer is to pre validate forms before making
transmissions back to the server.
Asynchronous Layers
✔Normally, JavaScript operates in a Synchronous manner.
✔In this approach, a request sent to the server requires a response before
the next lines of code can be executed.
✔During the wait between request and response, the browser sits in a
loading state.
7/6/2021 Mrs. karthiga g 18cs63 18
JAVASCRIPT DESIGN PRINCIPLES
✔In this model, as certain events are triggered, the JavaScript sends the
HTTP requests to the server.
✔However, while waiting for the response, the rest of the application
functions normally, and the browser isn’t in a loading state.
let a = 1
let b = 2
console.log(‘Synchronous’)
console.log(a)
console.log(b)
Synchronous
JavaScript
The above script is a simple synchronous JavaScript.
This means, the above script will execute in a sequence. The output of the
script would be,
Synchronous
1
2
✔ We now introduce some asynchronous features into the script.
let a = 1
let b = 2 Synchronous
setTimeout( function() { 1
console.log(‘Asynchronous’) 2
}, 1000) Asynchronous
console.log(‘Synchronous’)
console.log(a)
console.log(b)
Asynchronous Javascript
✔The above script is asynchronous and does not execute in a sequence.
✔We make the above script asynchronous by introducing an asynchronous function in it.
Web crawler
✔A Web crawler, sometimes called a spider or spiderbot, is an internet
bot that systematically browses the World Wide Web, typically for the
purpose of Web indexing.
Browser plug-in
✔There are many uses of JavaScript that are not desirable to the end
user.
Text-based client
✔Some clients use a text-based browser.
✔Any text between the opening and closing tags will only be displayed to
users without the ability to load JavaScript.
✔It is often used to prompt users to enable JavaScript, but can also be used to
show additional text to search engines.
<script>
document.write("Hello World!")
</script>
<noscript>Your browser does not support JavaScript!</noscript>
Graceful Degradation
✔With this strategy we develop our site for the abilities of current
browsers.
✔For those users who are not using current browsers, we might provide
an alternate site or pages for those using older browsers that lack the
JavaScript (or CSS or HTML5) used on the main site.
✔The idea here is that the site is “degraded” (i.e., loses capability)
“gracefully”.
Progressive Enhancement
✔In this case, the developer creates the site using CSS, JavaScript, and
HTML features that are supported by all browsers of a certain age or
newer.
✔To that baseline site, the developers can now “progressively” (i.e., for
each browser) “enhance” (i.e., add functionality) to their site based on
the capabilities of the users’ browsers.
Inline JavaScript
Inline JavaScript refers to the practice of including JavaScript code directly
within certain HTML attributes. For example,
Embedded JavaScript
Embedded JavaScript refers to the practice of placing JavaScript code within a
<script> element.
<html>
<body>
<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</body>
</html>
5/27/2022 Mrs. karthiga g 18cs63 35
WHERE DOES JAVASCRIPT GO?
External JavaScript
✔It is always a good practice to separate HTML and JavaScript.
✔JavaScript supports this separation by allowing links to an external file that contains
the JavaScript.
<head>
<script type="text/JavaScript" src="greeting.js">
</script>
</head>
We start by having a look at some rules that must be followed while writing a
JavaScript.
✔Everything is type sensitive, including function, class, and variable names.
✔There is a === operator, which tests not only for equality but type
equivalence.
✔Null and undefined are two distinctly different states for a variable.
Variables
✔Variables in JavaScript are dynamically typed, meaning a variable can be an
integer, and then later a string, then later an object.
✔Hence we do not require the familiar types like int, char, and String for variable
declaration.
✔Instead, to declare a variable x, we use the var keyword, the name, and a
semicolon.
var x;
Values can be assigned to the variables either at the time of declaration or run
time.
var y = 0; // y is defined and initialized to 0
y = 4; //y is assigned the value of 4
Comparison Operators
Logical Operators
✔JavaScript includes Boolean operators, which allow us to build complicated
expressions.
✔The Boolean operators and, or, and not and their truth tables are listed below.
Conditional Operators
✔JavaScript’s syntax is almost identical to that of Java, or C when it comes to
conditional structures such as if and if else.
✔In this syntax the condition to test is contained within ( ) brackets with the body
contained in { } blocks.
Loops
Like conditionals, loops use the ( ) and { } blocks to define the
condition and the body of the loop.
While Loops
The most basic loop is the while loop, which loops until the
condition is not met.
var i = 0;
while(i < 10){
//do something with i
i++;
}
For Loops
This statement begins with the for keyword and has the components placed
between ( ) brackets, semicolon (;) separated.
for (var i = 0; i < 10; i++){
//do something with i
}
Functions
Functions are the building block for modular code in JavaScript.
They are defined by using the reserved word function and then the function
name and (optional) parameters.
Alert
The alert() function makes the browser show a pop-up to the user, with
whatever is passed being the message displayed.
✔The pop-up may appear different to each user depending on their browser
configuration.
✔This pop-up obscures the underlying web page, and no actions can be done
until the pop-up is dismissed.
alert ( "Good Morning" );
However, we can optionally catch these errors preventing disruption of the program
using the try–catch block.
try {
nonexistantfunction("hello");
}
catch(err) {
alert("An exception was caught:" + err);
}
✔The throw keyword stops normal sequential execution, just like the
built-in exceptions.
try {
var x = -1;
if (x<0)
throw "smallerthan0Error";
}
catch(err){
alert (err + "was thrown");
}
✔It should be noted that throwing an exception disrupts the sequential execution of a
program.
✔That is, when the exception is thrown all subsequent code is not executed until the
catch statement is reached.
✔Hence, try-catch and throw statements should be used for abnormal or exceptional
cases in your program. They should not be used as a normal way of controlling
flow.
5/27/2022 Mrs. karthiga g 18cs63 47
JAVASCRIPT OBJECTS
Constructors
Normally to create a new object we use the new keyword followed
by the class name, and ( ) brackets with n optional parameters
inside, separated by comma as follows:
Properties
✔Each object might have several properties defined.
✔A property can be accessed using dot notation where a dot between the
object name and the property references that property.
alert(someObject.property);
Methods
✔Objects can also have methods, which are functions associated with an
instance of an object.
✔These methods are called using the same dot notation as for properties,
but instead of accessing a variable, we are calling a method.
someObject.doSomething();
Arrays
✔Array objects can be created using the new syntax and calling the
object constructor.
var greetings = new Array();
✔To initialize the array with values, the variable declaration would
look like the following:
var greetings = new Array("Good Morning", "Good noon");
or
var greetings = ["Good Morning", "Good noon"];
Modifying an Array
We now look at some functions associated with the array object.
Math
✔The Math class allows one to access common mathematic functions and
common values quickly in one place.
✔This static class contains methods such as max(), min(), pow(), sqrt() and
exp().
✔Trigonometric functions such as sin(), cos() and arctan() are also provided
by the Math class.
✔In addition, many mathematical constants are defined such as PI, E(Euler’s
number).
Math.PI // 3.141592657
Math.sqrt(4); // square root of 4 is 2.
Math.random(); // random number between 0 and 1
String
✔The String class provides facilities to create and concatenate strings.
var greet = new String("Good"); // long form constructor
var greet = "Good"; // shortcut constructor
Date
The Date class allows us to quickly calculate the current date or create
date objects for particular dates.
✔This tree structure is formally called the DOM Tree with the root, or
topmost object called the Document Root.
Nodes
✔In the DOM, each
element within the HTML
document is called a
node.
✔All nodes in the DOM share a common set of properties and methods.
✔These properties and methods give some details about the nodes.
Document Object
✔The DOM document object is the root JavaScript object
representing the entire HTML document.
✔There are some HTML elements that have additional properties that can be accessed. These
properties are listed next.
5/27/2022 Mrs. karthiga g 18cs63 65
THE DOCUMENT OBJECT MODEL
Some Specific HTML DOM Element Properties for Certain Tag Types
✔For this, we first have a look at the most popular ways of displaying a
JavaScript output.
✔Once the element has been accessed, we can then add contents into
that element using the innerHTML property.
✔With this background let us now see how to modify the contents of an
element.
✔We now modify the contents of this <div> element using JavaScript as
follows.
var latest = document.getElementById("latestComment");
var oldMessage = latest.innerHTML;
latest.innerHTML = oldMessage + "<p>Updated this div with
JS</p>";
createTextNode()
The createTextNode() method creates a Text Node with the specified
text.
var t = document.createTextNode("Hello World");
Once a text node has been created, we create an element to hold this text
node.
✔Once the element is created, the text node in put into the element using the
appendChild() method.
createTextNode demo1
createTextNode demo2
appendChild demo
removeChild()
The removeChild() method removes a specified child node of the
specified element.
var list = document.getElementById("myList");
list.removeChild(list.childNodes[0]);
removeChild demo
className property
✔Another way of dynamically defining the style of an element is using
the className property.
✔Syntax
HTMLElementObject.className //Return the className
HTMLElementObject.className = class //Set the className
Additional Properties
value property
The value property sets or returns the value of the of a text field.
✔Many of the events are initiated by user actions but some are generated by the
browser itself.
✔There are several approaches by which JavaScript can handle events. The
popular approaches are:
✔Inline event handling
✔Listener approach
✔In the above example, the event that occurs is click and the handler to
that event is alert() method that displays a pop-up.
Listener Approach
✔The problem with the inline handler approach is that it does not make use of
layers, that is, it does not separate content from behaviour.
✔The listener approach separates all JavaScript code from the HTML
markup.
✔One limitation with this approach (and the inline approach) is that only one
handler can respond to any given element event.
✔This means, once a event handler has been defined for an element, no other
handler can be defined for the same element using the approach demonstrated
now.
Syntax
element.addEventListener(event, function);
✔The first parameter is the type of the event (like "click" or "mousedown" or
any other HTML DOM Event.)
✔The second parameter is the function we want to call when the event occurs.
Eventlistener demo1
Eventlistener demo2
Eventlistener demo3
✔Some more example of event handling using a user defined function and an
anonymous function is presented next.
Event Object
✔All the events that we encounter are DOM event objects.
✔An event object has several key properties. Some of them are:
✔Bubbles
✔Cancelable
✔preventDefault
Bubbles
✔The Bubbles property is a Boolean value.
✔If an event’s bubbles property is set to true then there must be an event handler
in place to handle the event.
✔If not, the event will bubble up to its parent and trigger an event handler there.
✔If the parent has no handler it continues to bubble up until it hits the document
root, and then it goes away, unhandled.
✔Syntax
event.bubbles // returns TRUE or FALSE
Cancelable
✔The Cancelable property is also a Boolean value that indicates whether
or not the event can be cancelled.
preventDefault
The default action of an event is canceled using the preventDefault()
method.
Event types
✔There are several classes of events, with several types of event within each
class specified by the W3C.
✔Mouse Events
✔Mouse events are defined to capture a range of interactions driven by the
mouse.
✔The mouse events can be further categorized as mouse click and mouse move
events.
✔The user could be moving the mouse off one <div> and onto another in the
same moment, triggering onmouseon and onmouseout events as well as the
onmousemove event.
✔Keyboard Events
Events that occur when user presses a key on the keyboard, belongs to the
KeyboardEvent Object.
✔The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC)
in all browsers.
✔Hence it is better to use the onkeydown event instead, because it works for all
keys.
Form Events
Forms are the main means by which user input is collected and transmitted
to the server.
✔The most common JavaScript listener for forms is the onsubmit event.
In this section we will be seeing how to validate certain aspects of a form and how a
form is submitted.
Writing code to prevalidate forms on the client side will reduce the number of
incorrect submissions, thereby reducing server load.
This method checks whether its argument represents a numeric value. If so, it
returns true. Otherwise it returns false. The argument can be of any type.
5/27/2022 Mrs. karthiga g 18cs63 94
FORMS
Submitting Forms
Submitting a form using JavaScript requires having a node variable for the
form element.
Once the variable, say, formExample is acquired, one can simply call the
submit() method:
✔For this, Web Hosting is needed. Web Hosting is the process of renting or
buying space to house a website on the World Wide Web.
✔However, the major distinction is that our software runs on a web server
and uses the HTTP request-response loop for most interactions with the
clients.
✔Client side JavaScript code is downloaded at the client and is executed there.
✔In contrast, server-side source code remains hidden from the client as it is
processed on the server.
✔The clients never get to see the code. Only the HTML output from the script
is seen.
✔A server script can access resources on the web server whereas the client
cannot.
✔The following figure illustrates how client and server scripts differ.
✔The most commonly used resource is Data Storage, often in the form of a
connection to a Database Management System.
✔The next suites of resources are Web Services, often offered by third-party
providers.
✔Web services use the HTTP protocol to return XML or other data formats.
Using other software means, server applications can also send and receive
email, access user authentication services etc.
ASP.NET
✔ASP.NET is part of Microsoft’s .NET Framework and can use any .NET
programming language like C#.
✔ASP.NET uses an explicitly object-oriented approach and that is why it takes longer
to learn ASP.NET than ASP or PHP.
✔ASP.NET uses special markup called web server controls that encapsulate common
web functionality such as database-driven lists, form validation, and user registration
wizards.
✔ASP.NET pages are compiled into an intermediary file format called MSIL that is
analogous to Java’s byte-code.
✔ASP.NET then uses a JIT (Just-In-Time) compiler to compile the MSIL into machine
executable code.
Node.js
✔This is a more recent server environment that uses JavaScript on the server
side.
✔Unlike the other development technologies listed here, node.js is also its
own web server software, thus eliminating the need for Apache, IIS, or
some other web server software.
Perl
✔Perl was the language typically used for early server-side web development.
✔It was commonly used in conjunction with the Common Gateway Interface
(CGI), an early standard API for communication between applications and
web server software.
PHP(Hypertext Processor)
✔PHP is a dynamically typed language that can be embedded directly within
the HTML.
✔By default, PHP pages are compiled into an intermediary representation
called opcodes that are analogous to Java’s byte-code or the .NET
Framework’s MSIL.
Python
✔Python is an object-oriented programming language has many uses,
including being used to create web applications.
✔It is also used in a variety of web development frameworks.
Ruby on Rails
✔This is a web development framework that uses the Ruby programming
language.
✔Like ASP.NET and JSP, Ruby on Rails also emphasizes the use of MVC
design pattern.
✔It integrates features such as templates and engines that aim to reduce the
amount of development work required in the creation of a new site.
<?php
# single-line comment
/*
This is a multiline comment.
They are a good way to document
functions or complicated blocks of
code
*/
$artist = readDatabase(); //
end-of-line comment
?>
$count = 42;
String Letters
Just as with any language, writing code in the main function (which in
PHP is equivalent to coding in the markup between <?php and ?>
tags) is not a good habit to get into.
A function in PHP contains a small bit of code that accomplishes one
thing. In PHP there are two types of function: user-defined functions
and built-in functions.
1. A user-defined function is one that you the programmer define.
2. A built-in function is one of the functions that come with the
PHP environment
Now that you have defined a function, you are able to use it
whenever you want to. To call a function you must use its name
with the () brackets.
$output = getNiceTime();
echo getNiceTime();
If the function doesn’t return a value, you can just call the
function:
outputFooterMenu();
✔Variables defined in the main script are said to have global scope.
✔PHP does allow variables with global scope to be accessed within a function
using the global keyword