You are on page 1of 38

WEBPROG PRELIMS

Lecture 1
INTRODUCTION TO
JAVASCRIPT
What is JavaScript?
• a dynamic computer programming language
• lightweight and most commonly used as a part of
web pages, whose implementations allow client-side
script to interact with the user and make dynamic
pages
• an interpreted programming language with object-
oriented capabilities
• The programs in this language are called scripts.
• can be written right in a web page’s HTML and run
automatically as the page loads
• Scripts are provided and executed as plain text. They
don’t need special preparation or compilation to run.
What is JavaScript? p2
• JavaScript is very different from another language called
Java.
• JavaScript initially had another name: “LiveScript”. But
Java was very popular at that time, so it was decided that
positioning a new language as a “younger brother” of Java
would help.
• As JavaScript evolved, it became a fully independent
language with its own specification called ECMAScript, and
now it has no relation to Java at all.
• JavaScript can execute not only in the browser, but also on
the server, or actually on any device that has a special
program called the JavaScript engine.
• The browser has an embedded engine sometimes called a
“JavaScript virtual machine”.
JavaScript History
• JavaScript, originally called LiveScript, was created by
Brendan Eich at Netscape in 1995.
• Soon after, Microsoft launched its own version of
JavaScript called JScript.
• Subsequently, Netscape submitted it to ECMA (formerly
"European Computer Manufacturers Association", now
"Ecma International - European association for
standardizing information and communication systems")
for standardization, together with Microsoft's JScript.
Versions
The ECMA Specification is called "ECMA-262 ECMAScript
Language Specification" (also approved as "ISO/IEC
16262"):
• ECMA-262 version 1 (June 1997)
• ECMA-262 version 2 (August 1998)
• ECMA-262 version 3 (December 1999)
• ECMA-262 version 4 - abandon due to political
differences
• ECMA-262 version 5 and 5.1 (June 2011) (@
http://www.ecma-
international.org/publications/standards/Ecma-262.htm)
• ECMA-262 version 6: June 2015.
What Is ECMAScript?
• ECMAScript (European Computer Manufacturers Association
Script) is sometimes abbreviated as "ES“.
• is a scripting language specification maintained and trademarked
by Ecma International
• ECMA developed the official standard for ECMAScript, often
known as ECMA-262 which helps in defining the ECMAScript
language and also ensures the consistency between web script
implementations.
• JavaScript, JScript and ActionScript are implementation of
ECMAScript.
• ECMAScript, along with Document Object Model, works similarly
to the current implementations of JScript and JavaScript.
NOTE: ECMAScript evolves over time which means new features
are added and new syntax is adopted. Not all browsers will
implement all newer features of ECMAScript in the same manner.
The ECMA-262 Specification defined a standard version of the core JavaScript language:

• JavaScript is a lightweight, interpreted


programming language.
• Designed for creating network-centric
applications (applications that send data to the
server and are interconnected by a
communications network).
• Complementary to and integrated with Java.
• Complementary to and integrated with HTML.
• Open and cross-platform
Server-side scripting
• any scripting or programming that can run on the web server
• operations like customization of a website, dynamic change in the
website content, response generation to the user’s queries,
accessing the database, and so on are performed at the server
end.
• The server-side scripting constructs a communication link
between a server and a client (user).
• Earlier the server side scripting is implemented by the CGI
(Common Gateway Interface) scripts. The CGI was devised to
execute the scripts from programming languages such as C++ or
Perl on the websites.
• The server-side involves three parts:
• server,
• database,
• API’s and back-end web software developed by the server-side
scripting language.
Server-side scripting Process
1. When a browser sends a request to the server for a
webpage consisting of server-side scripting, the web
server processes the script prior to serving the page to
the browser.
2. Processing of a script could include extracting
information from a database, making simple
calculations, or choosing the appropriate content that is
to be displayed in the client end.
3. The script is being processed and the output is sent to
the browser.
4. The web server abstracts the scripts from the end user
until serving the content, which makes the data and
source code more secure.
Server-side scripting languages
• PHP: It is the most prevalent server-side language used
on the web which was designed to extract and manipulate
information in the database. The language is used in
association with SQL language for the Database. It is
used in Facebook, WordPress and Wikipedia.
• Python: The language is fast and contains shorter code.
It is good for beginners as it concentrates on the
readability and simplicity of the code. Python functions
well in the object-oriented environment and used in
famous sites like Youtube, Google, etc.
• Ruby: It contains complex logic which packages the back-
end with database utility which can also be provided by
PHP and SQL.
Client-side Scripting
• performed to generate a code that can run on the client
end (browser) without needing the server side processing
• scripts are placed inside an HTML document
• The client-side scripting can be used to examine the
user’s form for the errors before submitting it and for
changing the content according to the user input.
• The effective client-side scripting can significantly reduce
the server load.
• It is designed to run as a scripting language utilizing a
web browser as a host program.
Client-side scripting needs….
• HTML: It is the fundamental building blocks of web
programming which provides the frame to the website. It
describes the arrangement of the content.
• CSS: CSS provides the way to design the graphic
elements which help in making the appearance of the web
application more attractive.
• JavaScript: It is a client-side scripting language which
essentially devised for the specific purpose, but currently
there are various JavaScript frameworks used as server-
side scripting technology.
Server-side Scripting vs. Client-side Scripting

1. Server-side scripting is used at the backend, where the


source code is not viewable or hidden at the client side
(browser). On the other hand, client-side scripting is
used at the front end which users can see from the
browser.
2. When a server-side script is processed it communicates
to the server. As against, client-side scripting does not
need any server interaction.
3. The client-side scripting language involves languages
such as HTML, CSS and JavaScript. In contrast,
programming languages such as PHP, ASP.net, Ruby,
ColdFusion, Python, C#, Java, C++, etc.
Server-side Scripting vs. Client-side Scripting p2

4. Server-side scripting is useful in customizing the web


pages and implement the dynamic changes in the
websites. Conversely, the client-side script can effectively
minimize the load to the server.
5. Server-side scripting is more secure than client-side
scripting as the server side scripts are usually hidden
from the client end, while a client-side script is visible to
the users.
6. The client-side scripting emphasize on making the
interface of the web application or website more
appealing and functional. Conversely, server-side
scripting emphasizes on the data accessing methods,
error handling and fast processing etcetera.
Advantages of JavaScript
• Speed. It can be run immediately within the client-side
browser. It also has no need to be compiled on the client side.
• Simplicity. JavaScript is relatively simple to learn and
implement.
• Popularity. JavaScript is used everywhere in the web.
• Interoperability. JavaScript plays nicely with other languages
and can be used in a huge variety of applications. Unlike PHP
or SSI scripts, JavaScript can be inserted into any web page
regardless of the file extension. JavaScript can also be used
inside scripts written in other languages such as Perl and PHP.
• Server Load. Being client-side reduces the demand on the
website server.
• Rich interfaces. Drag and drop components or slider may
give a rich interface to your website.
Advantages of JavaScript p2
• Extended Functionality. Third party add-ons like
Greasemonkey enable JavaScript developers to write
snippets of JavaScript which can execute on desired web
pages to extend its functionality.
• Versatility. Nowadays, there are many ways to use
JavaScript through Node.js servers. If you were to
bootstrap node.js with Express, use a document database
like mongodb, and use JavaScript on the front-end for
clients, it is possible to develop an entire JavaScript app
from front to back using only JavaScript.
• Updates. ECMA International is dedicated to updating
JavaScript annually.
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. Whereas server-side
scripts will always produce the same output, client-side
scripts can be a little unpredictable. Don’t be overly
concerned by this though - as long as you test your script
in all the major browsers you should be safe. Also, there
are services out there that will allow you to test your code
automatically on check in of an update to make sure all
browsers support your code.
The HTML DOM
• The HTML Document Object Model (DOM) is the
browser's view of an HTML page as an object hierarchy,
starting with the browser window itself and moving deeper
into the page, including all of the elements on the page
and their attributes.

A Simplified Version
Of The HTML DOM.
The HTML DOM p2
• With the object model, JavaScript gets all the power it
needs to create dynamic HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and
attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the
page
• JavaScript can create new HTML events in the page
The HTML DOM p3
HTML DOM defines:
• The HTML elements as objects
• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

In other words: The HTML DOM is a standard for how to


get, change, add, or delete HTML elements.
JavaScript Syntax
• JavaScript can be implemented using JavaScript
statements that are placed within the <script>... </script>
HTML tags in a web page.
• You can place the <script> tags, containing your
JavaScript, anywhere within your web page. But, it is a
good practice to add JavaScript in the footer i.e. just
before closing the <body> tag. This is because:
• It loads script faster.
• It will not block any DOM content to load.
• It loads the web page before loading JavaScript
• Improves display speed
• Page loads faster
JavaScript Syntax p2
• The <script> tag alerts the browser program to
start interpreting all the text between these tags
as a script. A simple syntax of your JavaScript will
appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
• Language − This attribute specifies what scripting
language you are using. Typically, its value will be
javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this
attribute.
• Type − This attribute is what is now recommended to
indicate the scripting language in use and its value should
be set to "text/javascript".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Basic Rules
• JavaScript statements end with semi-colons.
• JavaScript is case sensitive.
• JavaScript has two forms of comments:
• Single-line comments begin with a double slash (//).
• Multi-line comments begin with "/*" and end with "*/".

Comments Syntax
// This is a single-line comment.
/*
This is a
multi-line
comment.
*/
Accessing Elements
• Dot Notation - elements (and other objects) can be
referenced using dot notation, starting with the highest-
level object (i.e., window). Objects can be referred to by
name or id or by their position on the page. For example,
if there is a form on the page named "loginform", using dot
notation you could refer to the form as follows:
Syntax
window.document.loginform
Assuming that loginform is the first form on the page, you
could also refer to it in this way:
Syntax
window.document.forms[0]
Accessing Elements p2
• A document can have multiple form elements as children.
• The number in the square brackets ([]) indicates the
specific form in question.
• Every document object contains a collection of forms.
• The length of the collection could be zero (meaning there
are no forms on the page) or greater.
• In JavaScript, collections (and arrays) are zero-based,
meaning that the first form on the page is referenced with
the number zero (0) as shown in the syntax example on
the previous slide.
Accessing Elements p3
• Square Bracket Notation
• Objects can also be referenced using square bracket
notation as shown below:
Syntax
window['document']['loginform']
// and
window['document']['forms'][0]
• Dot notation and square bracket notation are completely
interchangeable.
• Dot notation is much more common; however, there are
times when it is more convenient to use square bracket
notation.
Where Is JavaScript Code Written?
• JavaScript code can be written inline (e.g., within HTML
attributes called on-event handlers), in script blocks, and in
external JavaScript files.
Code Sample javascript.html:
<!DOCTYPE html>
<html >
<head>
<script>
//Pop up an alert
window.alert("The page is loading");
</script>
<title>JavaScript Page</title>
</head>
Where Is JavaScript Code Written? p2
<body>
<main>
<button onclick="document.body.style.backgroundColor = 'red';">
Red
</button>
<button onclick="document.body.style.backgroundColor = 'white';">
White
</button>
<button onclick="document.body.style.backgroundColor = 'green';">
Green
</button>
<button onclick="document.body.style.backgroundColor = 'blue';">
Blue
</button>
<script src="script-2.js"></script>
</main>
</body>
</html>
Where Is JavaScript Code Written? p3
• Code Sample script.js :
• /*
• This script simply outputs
• "Hello, there!" to the browser.
• */
• document.write("<p>Hello, there!</p>");
The Implicit window Object
• The window object is always the implicit top-level object
and therefore does not have to be included in references
to objects.
• For example, window.document.write() can be shortened
to document.write().
• Likewise, window.alert() can be shortened to just alert().
JavaScript Objects, Methods and Properties
• JavaScript is used to manipulate or get information about
objects in the HTML DOM. Objects in an HTML page have
methods (actions, such as opening a new window or
submitting a form) and properties (attributes or qualities,
such as color and size).
• To illustrate objects, methods and properties, let's return
to the code in javascript.html and script.js.
Methods
• Methods are the verbs of JavaScript. They cause things to
happen.
window.alert() - HTML pages are read and processed from
top to bottom. Because window is the implicit top-level
object, we could leave it off and just write alert("The page is
loading"). When the browser reads that line of code, it will
pop up an alert box and will not continue processing the
page until the user presses the OK button. Once the user
presses the button, the alert box disappears and the rest of
the page loads.
document.write() - The write() method of the document
object is used to write out code to the page as it loads. It is
often used to write out dynamic data, such as the date and
time on the user's machine.
Arguments in Methods
• Methods can take zero or more arguments separated by
commas.
Syntax
object.method(argument1, argument2);

• The alert() and write() methods shown in the previous


example each take only one argument: the message to
show or the HTML to write out to the browser.
Properties
• Properties are the adjectives of JavaScript. They describe
qualities of objects and, in some cases are writable (can be
changed dynamically).

document.body.style.backgroundColor
• The body object is a property of the document object
• The style object is a property of the body object
• The backgroundColor is a read-write property of the style object.
• Looking back at javascript.html, the four button elements use the
onclick on-event handler to catch click events. When the user
clicks on a button, JavaScript is used to set the background of
the body to a new color, in the same way that we might use CSS
to style the page with background-color:red or background-
color:white.
Activity 1
Alerts, Writing, & Changing Background Color
• Duration: 5 to 15 minutes.
1. In this exercise, you will practice using JavaScript to pop up
an alert, write text to the screen, and set the background
color of the page.
2. Create an HTML document named activity1.html
3. In the head of the file, add a JavaScript alert which pops up
the message "Welcome to my page!" when the page loads.
4. Add click handlers to the two buttons to allow the user to
change the background color of the page to red or to blue.
5. In the script at the bottom of the page, use JavaScript to
write the text "This text was generated by JavaScript." to the
page.
6. Test your solution in a browser.
Code Explanation of Activity
• In the head, we use window.alert() to generate the popup.
We could have just used alert().
• We use document.write() to write to the screen at the
bottom of the page.
• We use onclick="document.body.style.backgroundColor =
'red'" and onclick="document.body.style.backgroundColor
= 'blue'" to add click handlers to the buttons.

You might also like