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

WT M3 JavaScript

JavaScript is a scripting language that runs in web browsers and allows for dynamic interactions. It is commonly used for client-side scripting to validate forms, modify page elements, and make asynchronous requests. JavaScript code can be included inline, embedded in <script> tags, or linked via external .js files.

Uploaded by

Janhvi Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

WT M3 JavaScript

JavaScript is a scripting language that runs in web browsers and allows for dynamic interactions. It is commonly used for client-side scripting to validate forms, modify page elements, and make asynchronous requests. JavaScript code can be included inline, embedded in <script> tags, or linked via external .js files.

Uploaded by

Janhvi Singh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

JavaScript

What Is JavaScript and What Can It Do?

• JavaScript and Java are vastly different programming languages with


different uses.
• Java is a full-fledged compiled, object oriented language, popular for
its ability to run on any platform with a Java Virtual Machine
installed.
• JavaScript is one of the world’s most popular languages, with fewer of
the object-oriented features of Java, and runs directly inside the
browser, without the need for the JVM.
• JavaScript is object oriented in that almost everything in the language
is an object.
• For instance, variables are objects in that they have constructors,
properties, and methods.
• JavaScript is dynamically typed in that variables can be easily (or
implicitly) converted from one data type to another.
• With JavaScript, the type of data a variable can hold is assigned at
runtime and can change during run time as well.
• The idea of client-side scripting is an important one in web
development. It refers to the client machine (i.e., the browser)
running code locally rather than relying on the server to execute
code and return the result.
• Client-Side Languages - Flash, VBScript, Java, and JavaScript. Some
of these work with browsers & others requires plug-ins to
functions.
• Figure 6.1 illustrates how a client machine downloads and
executes JavaScript code.
• There are many advantages of client-side scripting:
• Processing can be offloaded from the server to client
machines, thereby reducing the load on the server.
• The browser can respond more rapidly to user events than a
request to a remote server ever could, which improves the
user experience.
• JavaScript can interact with the downloaded HTML in a way
that the server cannot, creating a user experience more like
desktop software than simple HTML ever could.
• The disadvantages of client-side scripting are mostly related to
how programmers use JavaScript in their applications.
• Some of these include:
• There is no guarantee that the client has JavaScript enabled,
meaning any required functionality must be housed on the
server, despite the possibility that it could be offloaded.
• JavaScript-heavy web applications can be complicated to debug
an maintain.
• JavaScript has often been used through inline HTML hooks that
are embedded into the HTML of a web page, which decreases
code readability, and increases the difficulty of web
development.
• Adobe Flash, which 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 also 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,
as shown in Figure 6.2.
• A browser plug-in is a software add-on that extends the
functionality and capabilities of the browser by allowing it to
view and process different types of web content.
• A JAVA applet is a term that refers to a small application that
performs a relatively small task.
• Java applets are written using the Java programming language
and are separate objects that are included within an HTML
document via the <applet> tag, downloaded, and then passed
on to a Java plug-in.
• The 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.
• Figure 6.3 illustrates how Java applets work in the web
environment.
• Disadvantage of both Flash plug-ins and Java applets.
• First, Java applets require the JVM be installed and up to date,
which some players are not allowing for security reasons
(Apple’s iOS powering iPhones and iPads supports neither Flash
nor Java applets).
• Second, Flash and Java applets also require frequent updates,
which can annoy the user and present security risks.
• With the universal adoption of JavaScript and HTML5, JavaScript
remains the most dynamic and important client-side scripting
language for the modern web developer.
• JavaScript’s History and Uses
• JavaScript was introduced by Netscape in their Navigator
browser back in 1996. It originally was called LiveScript.
• JavaScript is an implementation of a standardized scripting
language called ECMAScript.
• Internet Explorer (IE) at first did not support JavaScript, but
instead had its own browser-based scripting language
(VBScript).
• While IE now does support JavaScript, Microsoft
sometimes refers to it as JScript, primarily for trademark
reasons (Oracle currently owns the trademark for
JavaScript).
• In 1998, JavaScript was only slightly useful, had only a few
common uses: graphic roll-overs (that is, swapping one image
for another when the user hovered the mouse over an image),
pop-up alert messages, scrolling text in the status bar, opening
new browser windows, and prevalidating user data in online
forms.
• In the middle of the 2000s, JavaScript merge with AJAX -
Asynchronous JavaScript and XML, refers to a style of website
development that makes use of JavaScript to create more
responsive user experiences.
• The responsiveness is created is via asynchronous data requests
via JavaScript and the XMLHttpRequest object.
• This addition to JavaScript was introduced by Microsoft as an
ActiveX control (the IE version of plug-ins) in 1999, but it wasn’t
until sophisticated websites by Google (such as Gmail and Maps)
and Flickr demonstrated what was possible using these
techniques that the term AJAX became popular.
• Figure 6.4 illustrates the processing flow for a page that requires
updates based on user input using the normal synchronous non-
AJAX page request-response loop.
• In Figure 6.4, interaction requires multiple requests to the server,
which not only slows the user experience, it puts the server
under extra load since each request is invoking a server-side
script.
• In Figure 6.5, when the multiple requests are being made across
the Internet to a busy server, then the time costs of the normal
HTTP request-response loop will be more visually noticeable to
the user.
• AJAX provides a way to avoid the visual and temporal deficiencies
of normal HTTP interactions.
• With AJAX web pages, it is possible to update sections of a page
by making special requests of the server in the background.
• Figure 6.6 illustrates how the interaction shown in Figure 6.4
would differ in an AJAX-enhanced web page.
• JavaScript frameworks - jQuery, Prototype, ASP.NET AJAX, and
MooTools are developed, which reduces the amount of JavaScript
code required to perform typical AJAX tasks.
JavaScript Design Principles
• The principles increase the quality and reusability of the code while
making it easier to understand, and hence more maintainable.
• In object-oriented programming, a software layer is a way of
conceptually grouping programming classes that have similar
functionality and dependencies.
• Common software design layer names include:
• Presentation layer. Classes focused on the user interface.
• Business layer. Classes that model real-world entities, such as
customers, products, and sales.
• Data layer. Classes that handle the interaction with the data
sources. Figure 6.8 illustrates the idea of JavaScript layers.
• Presentation Layer
• This type of programming focuses on the display of information.
• JavaScript can alter the HTML of a page, which results in a
change, visible to the user.
• These presentation layer applications include common things
like creating, hiding, and showing divs, using tabs to show
multiple views, or having arrows to page through result sets.
• This layer is most closely related to the user experience and the
most visible to the end user.
• 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. It is
used with the presentation layer to create a coherent user
experience.
• Both layers exist on the client machine, although the
intention is to prevalidate forms before making
transmissions back to the server.
• Asynchronous Layers
• Normally, JavaScript operates in a synchronous manner where 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 and only updates
upon receiving the response.
• An asynchronous layer can route requests to the server in the
background. In this model, as events are triggered, the JavaScript
sends the HTTP requests to the server, but while waiting for the
response, the rest of the application functions normally, and the
browser isn’t in a loading state.
Figure 6.11 Example of graceful degradation
Figure 6.12 Site with Progressive Enhancements
Where Does JavaScript Go?
• JavaScript can be linked to an HTML page in a number of ways.
Just as CSS styles can be inline, embedded, or external, JavaScript
can be included in a number of ways.
• Inline JavaScript
• Inline JavaScript refers to the practice of including JavaScript code
directly within certain HTML attributes, such as that shown in
Listing 6.1.
• Embedded JavaScript
• Embedded JavaScript refers to the practice of placing JavaScript
code within a <script> element as shown in Listing 6.2.

• External JavaScript
• JavaScript external files have the extension .js.
• These external files typically contain function definitions, data
definitions, and other blocks of JavaScript code.
• In Listing 6.3, the link to the external JavaScript file is placed
within the <head> element.
Syntax
• The fundamental syntax for the most common programming
constructs including variables, assignment, conditionals,
loops, and arrays
• Everything is type sensitive, including function, class, and variable names.
• The scope of variables in blocks is not supported. This means variables
declared inside a loop may be accessible outside of the loop, counter to
what one would expect.
• There is a === operator, which tests not only for equality but type
equivalence.
• Null and undefined are two distinctly different states for a variable.
• Semicolons are not required, but are permitted (and encouraged).
• There is no integer type, only number, which means floating-point
rounding errors are prevalent even with values intended to be integers.
JavaScript Objects
• JavaScript is not a full-fledged object-oriented programming
language since it does not have classes and it does not support
inheritance and polymorphism.
• The language support objects. User-defined objects are declared
in a way like C++ or Java.
• Objects can have constructors, properties, and methods
associated with them, and are used like objects in other object-
oriented languages.
• Constructors
• Normally to create a new object we use the new keyword, the
class name, and ( ) brackets with n optional parameters inside,
comma delimited as follows:
var someObject = new ObjectName(parameter 1,param 2,..., parameter n);
• For example, a String object can be defined with the shortcut
var greeting = "Good Morning";
• Instead of the formal definition
var greeting = new String("Good Morning");
• Properties
• Each object might have properties that can be accessed,
depending on its definition. When a property exists, it can be
accessed using dot notation where a dot between the instance
name and the property references that property.
alert(someObject.property); //show someObject.property
to the user
• 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();
• Methods may produce different output depending on the object
they are associated with because they can utilize the internal
properties of the object.
• Objects Included in JavaScript
• A number of objects are included with JavaScript. These include
Array, Boolean, Date, Math, String, and others.
• In addition to these, JavaScript can also access Document Object
Model (DOM) objects that correspond to the content of a page’s
HTML.
• These DOM objects let JavaScript code access and modify HTML
and CSS properties of a page dynamically.
• Arrays
• Arrays are one of the most used data structures, and they have
been included in JavaScript as well.
• Objects can be created using the new syntax and calling the object
constructor.
• The following code creates a new, empty array named greetings:
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 Afternoon");
• or, using the square bracket notation:
var greetings = ["Good Morning", "Good Afternoon"];
• Accessing and Traversing an Array
• To access an element in the array you use the familiar square
bracket notation from Java and C-style languages, with the index
you wish to access inside the brackets.
alert ( greetings[0] );
• An array can be traverse through the items sequentially. The
following for loop quickly loops through an array, accessing
the ‘i’th element each time using the Array object’s length
property to determine the maximum valid index.
• It will alert “Good Morning” and “Good Afternoon” to the
user.
for (var i = 0; i < greetings.length; i++)
{
alert(greetings[i]);
}
• Modifying an Array
• To add an item to an exitsing array, you can use the push
method.
greetings.push("Good Evening");

• The pop method can be used to remove an item from the back of
an array. Additional methods that modify arrays include concat(),
slice(), join(), reverse(), shift(), and sort().
• 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(), and trigonometric functions such as sin(), cos(),
and arctan().
• In addition, many mathematical constants are defined such as PI,E
(Euler’s number), SQRT2, and some others as shown in Listing 6.7.
• String
• The new syntax to create a String object is as follows:
var greet = new String("Good"); // long form constructor
var greet = "Good"; // shortcut constructor
• To get the length of a string, length property is used.
alert (greet.length); // will display "4"
• Another common way to use strings is to concatenate them
together. The + operator has been overridden to allow for
concatenation in place.
var str = greet.concat("Morning"); // Long form concatenation
var str = greet + "Morning"; // + operator concatenation
• Many other useful methods exist within the String class, such as
accessing a single character using charAt(), or searching for one
using indexOf(). Strings allow splitting a string into an array,
searching and matching with split(), search(), and match() methods.
• To display today’s date as a string, we would simply create a new
object and use the toString() method.
var d = new Date();
// This outputs Today is Mon Nov 12 2012 15:40:19 GMT-0700
alert ("Today is "+ d.toString());
The Document Object Model (DOM)
• JavaScript is almost always used to interact with the HTML
document in which it is contained. As such, there needs to be
some way of programmatically accessing the elements and
attributes within the HTML. This is accomplished through a
programming interface (API) called the Document Object Model
(DOM).
• Nodes
• In the DOM, each element within the HTML document is called a
node.
• If the DOM is a tree, then each node is an individual branch. There are
element nodes, text nodes, and attribute nodes, as shown in Figure
6.18.
• All nodes in the DOM share a common set of properties and
methods. Thus, most of the tasks that we perform in JavaScript
involve finding a node, and then accessing or modifying it via those
properties and methods.
• The most important of these are shown in Table 6.3.
• Document Object
• The DOM document object is the root JavaScript object
representing the entire HTML document.
• It contains some properties and methods that will use in our
development and is globally accessible as document.
• The attributes of this object include some information about the
page including doctype and inputEncoding.
• Accessing the properties is done through the dot notation.
• Element Node Object
• The type of object returned by the method
document.getElementById() is an element node object. This
represents an HTML element in the hierarchy, contained
between the opening <> and closing </> tags for this element.
• IDs must be unique in an HTML document, getElementByID()
returns a single node. The returned Element Node object has
the node properties shown in Table 6.3.
• Table 6.6 lists some common additional properties and the
HTML tags that have these properties.
• Modifying a DOM Element
• In JavaScript, the document.write() method is used to create
output to the HTML page from JavaScript.
• Using the DOM document and HTML DOM element objects, we
can do exactly that using the innerHTML property as shown in
Listing 6.8
• DOM functions create- TextNode(), removeChild(), and
appendChild() allow us to modify an element in a more rigorous
way as shown in Listing 6.9.
• Changing an Element’s Style
• We can also modify the style associated with a particular block.
We can add or remove any style using the style or className
property of the Element node.

• Note that the style property is itself an object, specifically a


CSSStyleDeclaration type, which includes all the CSS attributes as
properties and computes the current style from inline, external,
and embedded styles.
• The className property is normally a better choice, because it
allows the styles to be created outside the code, and thus be
better accessible to designers.
• Using this model we would change the background color by
having two styles defined, and changing them in JavaScript code.
var commentTag = document.getElementById("specificTag");
commentTag.className = "someClassName";
• HTML5 introduces the classList element, which allows you to add,
remove, or toggle a CSS class on an element. You could add a
class with
label.classList.addClass("someClassName");
• Additional Properties
• In addition to the global properties present in all tags, there are
additional methods available when dealing with certain tags.
Table 6.6 lists a few common ones.
• JavaScript Events
• A JavaScript event is an action that can be detected by JavaScript.
• Many of events are initiated by user actions but some are
generated by the browser itself.
• An event is triggered and then it can be caught by JavaScript
functions, which then do something in response.
• In the original JavaScript, events could be specified right in the
HTML markup with hooks to the JavaScript code. This mechanism
was popular throughout the 1990s and 2000s.
• As more powerful frameworks were developed, this original
mechanism was replaced by the listener approach.
• A visual comparison of the old and new technique is shown in
Figure 6.20.
• Inline Event Handler Approach
• JavaScript events allow the programmer to react to user
interactions. For example, if you wanted an alert to pop-up
when clicking a <div> you might program:

• In this example the HTML attribute onclick is used to attach a


handler to that event. When the user clicks the <div>, the
event is triggered and the alert is executed.
• This reduces the ability of designers to work separately from
programmers but complicates maintenance of applications.
• The better way to program this is to remove the JavaScript
from the HTML.
• Listener Approach

• The first line creates a temporary variable for the HTML element that
will trigger the event. The next line attaches the HTML element’s
onclick event to the event handler, which invokes the JavaScript alert()
method.
• The main advantage of this approach is that this code can be written
anywhere, including an external file that helps uncouple the HTML
from the JavaScript.
• The limitation with this approach is that only one handler can respond
to any given element event.
• The use of addEventListener() shown in 6.11 was introduced in DOM
Version 2.
• This approach has all the other advantages of the approach shown in
6.10, and has the additional advantage that multiple handlers can be
assigned to a single object’s event.

• The examples in 6.10 and 6.11 uses the built-in JavaScriptalert()


function.
• Event Object
• No matter which type of event we encounter, they are all DOM event
objects and the event handlers associated with them can access and
manipulate them.
• Typically, the events passed to the function handler as a parameter
named e.
function someHandler(e) {
// e is the event that triggered this handler.
}
• These objects have many properties and methods. Many of these
properties are,
• 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 or it 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.
• Cancelable. The Cancelable property is also a Boolean value that
indicates whether or not the event can be cancelled.
• If an event is cancelable, then the default action associated with it
can be canceled.
• A common example is a user clicking on a link. The default action
is to follow the link and load the new page.
• preventDefault. A cancelable default action for an event can be
stopped using the preventDefault() method as shown in 6.14.

• This is a common approach when you want to send data


asynchronously when a form is submitted, for example, since
the default event of a form submit click is to post to a new URL.
• Event Types
• There are several classes of event, with several types of event
within each class specified by the W3C. The classes are mouse
events, keyboard events, form events, and frame events.
• Mouse Events
• Mouse events are defined to capture a range of interactions
driven by the mouse. These can be further categorized as mouse
click and mouse move events.
• Table 6.7 lists the possible events one can listen for from the
mouse.
• Keyboard Events
• Form Events
• Forms are the main means by which user input is collected and
transmitted to the server. Table 6.9 lists the different form events.
• Frame Events
• Frame events are the events related to the browser frame that
contains your web page. The most important event is the onload
event, which tells us an object is loaded and therefore ready to work
with.
• Forms
• Validating Forms
• Form validation is one of the most common applications of JavaScript.
• Writing code to prevalidate forms on the client side will reduce the
number of incorrect submissions, thereby reducing server load.
Although validation must still happen on the server side, JavaScript
prevalidation is a best practice.
• There are a number of common validation activities including email
validation, number validation, and data validation.
• Empty Field Validation
• A common application of a client-side validation is to make sure the
user entered something into a field.
• The way to check for an empty field in JavaScript is to compare
a value to both null and the empty string ("") to ensure it is not
empty, as shown in 6.18.
• Number Validation
• Number validation can take many forms. There is no simple
functions exist for number validation.
• Using parseInt(), isNAN(), and isFinite(), you can write your own
number validation function.
• Submitting Forms
• Submitting a form using JavaScript requires having a node variable
for the form element. Once the variable is acquired, one can
simply call the submit() method.

You might also like