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

WEB

DEVELOPMENT
(JAVASCRIPT)
By: Vera A. Panaguiton
OUTLINE
WHAT IS JAVASCRIPT?
VARIABLES
CONDITIONALS
FUNCTIONS
OBJECTS
DOM
AJAX
JQUERY
APDEV 1 by Vera A. Panaguiton 2
WHAT IS A JAVASCRIPT?
JavaScript is a lightweight, cross-platform and
interpreted programming language with object oriented
capabilities.
It is originally called LiveScript and was developed by
Brendan Eich at Netscape in 1995 and was shipped with
Netscape Navigator 2.0 beta releases.
It is well-known for the development of web pages, many
non-browser environments also use it. JavaScript can be
used for Client-side developments as well as Server-
side developments.
JavaScript syntax is similar to C, Perl, and Java; for example,
if statements, while and for loops are almost identical.
APDEV 1 by Vera A. Panaguiton 3
PLATFORMS FOR JAVASCRIPT
Web Development
Adding interactivity and behavior to static sites. (Use AngularJS)
Web Applications
With technology, browsers have improved to the extent that a language was required to create robust web
applications. When we explore a map in Google Maps then we only need to click and drag the mouse. All
detailed view is just a click away. It uses Application Programming Interfaces(APIs) that provide extra power to
the code. (Electron and React is helpful in this department)
Server Applications
JavaScript made its way from client to server with the help of node.js, the most powerful in the server-side.
Games
JavaScript also helps in creating games for leisure. The combination of JavaScript and HTML 5 makes JavaScript
popular in game development as well. (Use EaseJS library which provides solutions for working with rich
graphics)
Smartwatches
JavaScript is being used in all possible devices and applications. This framework works for applications that
require the internet for its functioning. (Use PebbleJS library which is used in smartwatch applications).
Art
Artists and designers can create whatever they want using JavaScript to draw on HTML 5 canvas, make sound
more effective also can be used p5.js library.
Machine Learning
This JavaScript ml5.js library can be used inAPDEV
web development
1 by Vera A. Panaguiton by using machine learning. 4
JAVASCRIPT FRAMEWORKS & LIBRARIES
Angular Ember.js
React Meteor
jQuery Mithril
Node.js Polymer
Vue.js Aurelia
Ext.js Backbone.js
APDEV 1 by Vera A. Panaguiton 5
The <script> tag
JavaScript can be placed in the body and head sections
of an HTML page with the help of the <script> tag.
The <script> tag contains javascript code which is
automatically executed when the browser processes the
tag.
The optional type=“text/javascript” is not needed in
HTML5 because it is the default type.

<script> </script>
APDEV 1 by Vera A. Panaguiton 6
How to insert javascript.

Inside <head></head>

Before the closing


</body> tag

APDEV 1 by Vera A. Panaguiton 7


JAVASCRIPT EXAMPLE: document.write
The function document.write writes a string into the HTML document.

CODE OUTPUT

APDEV 1 by Vera A. Panaguiton 8


JAVASCRIPT EXAMPLE : alert box
CODE OUTPUT

APDEV 1 by Vera A. Panaguiton 9


EXTERNAL JAVASCRIPT
Just like CSS, JavaScript can also be placed in
external files – practical when the same code is
used in many different web pages (file
extension is .js).
Use src attribute and the value should be the
url of your JavaScript file.

<script src=“js/scriptfile.js”></script>
APDEV 1 by Vera A. Panaguiton 10
JAVASCRIPT EXAMPLE : EXTERNAL FILE
CODES
OUTPUT

APDEV 1 by Vera A. Panaguiton 11


JAVASCRIPT DATATYPES
NUMBERS
JavaScript has only one type of numbers – can be written with
or without decimals.
STRINGS
A string (or a text string) is a series of characters written with
quotes.
BOOLEAN
Booleans can only have two values: true or false.
UNDEFINED
A variable without a value has the value undefined.
Null
No value assigned which is different from a 0
APDEV 1 by Vera A. Panaguiton 12
OTHER JAVASCRIPT DATATYPES
ARRAYS
Arrays in JavaScript are written with square brackets.

OBJECTS
Entities that typically represents elements of an HTML page.
JavaScript objects are written with curly braces with properties written as
name:value pairs, separated by commas.
Most important datatype and forms the building blocks for modern JavaScript

DYNAMIC TYPES
JavaScript has dynamic types – this means that the same variable can be used as
different types

Note: The typeof operator is used to find the type of a JavaScript variable.
APDEV 1 by Vera A. Panaguiton 13
Converting Between Data Types
There are a number of techniques for converting
between data types. To convert from a string several
parse and other functions are available.

parseFloat – Converts a string to a float


parseInt – Converts a string to an integer
Number – Converts a string to a number
toString – Converts a number to a string

APDEV 1 by Vera A. Panaguiton 14


Converting Between Data Types : Example
CODE
OUTPUT

APDEV 1 by Vera A. Panaguiton 15


JavaScript VARIABLES
Language specification for JavaScript is called the ECMAScript. ECMA is an
organization that standardize information.
ES2015 (ECMAScript publish on June 2015) introduced two important new
JavaScript keywords: let and const.

Before ES2015 , every variable is defined by the var keyword.


var var_name
After ES2015, we now have two new variable containers: let and const.
let is the same as var but different in scope
const variable value cannot and will not change through out the script.
let var_name
const var_name
APDEV 1 by Vera A. Panaguiton 16
RULES FOR VARIABLE NAMES(IDENTIFIERS)
Names can contain letters, digits, underscores,
and dollar signs.
Names must begin with a letter, $, or _
Names are case sensitive.
Reserved words cannot be used as names.

Note: JavaScript is a case-sensitive language

APDEV 1 by Vera A. Panaguiton 17


VARIABLES SCOPE
Block scope
-Can only be available inside the scope it is declared
like in for loop. Use let for block scope.
Function scope
-Variables declared with the var keyword is accessible
only within the function. Use var for block scope.
Global scope
-Accessible anywhere on the page. Variables without
var or let.
APDEV 1 by Vera A. Panaguiton 18
JAVASCRIPT RESERVED WORDS

APDEV 1 by Vera A. Panaguiton 19


Javascript VARIABLES : EXAMPLES

Note: Semi-colons are optional in JavaScript because of ASI (Automatic Semicolon Insertion) but omitting them can
lead to dire consequences on rare occasions. APDEV 1 by Vera A. Panaguiton 20
OPERATORS
Arithmetic Operators :
+, -, *, /, %, ++, --
Comparison (Relational) Operators :
==, !=, >, <, >=, <=
Logical Operators :
&&, ||, !
Assignment Operators:
=, +=, -=, *=, /=, %=

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
APDEV 1 by Vera A. Panaguiton 21
CONDITIONAL STATEMENTS
JavaScript supports conditional statements which are used
to perform different actions based on different conditions.
if
if else
if else if
switch
while
do while
for

Note: If you already know Java, then this is very easy for you.
APDEV 1 by Vera A. Panaguiton 22
Comments
JavaScript uses two types of comments:
single-line comments and multiline comments.

Single-line comments start with a double slashes:


// This is a comment

For multiline comments, use the /* */ symbols:


/* This is a block of comments
that continues for a number of lines
*/
APDEV 1 by Vera A. Panaguiton 23
DIALOG BOXES
JavaScript supports three important types of dialog boxes.
These dialog boxes can be used to raise and alert, or to get
confirmation on any input or to have a kind of input from
the users.

1. Alert Dialog Box


2. Confirmation Dialog Box
3. Prompt Dialog Box

APDEV 1 by Vera A. Panaguiton 24


alert Message Box
 An alert dialog box is mostly used to give a warning message to the
users.
 For example, if one input field requires to enter some text but the user
does not provide any input, then as a part of validation, you can use an
alert box to give a warning message.
 Alert box gives only one button "OK" to select and proceed.

alert(“An Alert Message”);

APDEV 1 by Vera A. Panaguiton 25


prompt Dialog Box
 The prompt dialog box provides a way of getting input from the user.
 It pops up with a simple textbox. After the user enters text, its value is returned.
 This method takes two arguments:
- a string of text that is normally displayed as a question to the user, prompting the user
to do something,
- and another string of text that is the initial default setting for the box. If this argument is
an empty string, nothing is displayed in the box.
 The prompt() method always returns a value. If the user clicks the OK button, all the text in
the box is returned; otherwise null is returned

var result = prompt("Name:","");

APDEV 1 by Vera A. Panaguiton 26


prompt Dialog Box : Example

APDEV 1 by Vera A. Panaguiton 27


Confirm Dialog Box
 The confirm dialog box is used to confirm a user’s answer to a question. The user
must agree before the action is completed.
 You’ll often see this when placing an online order or deleting a file where a yes or no
confirmation determines what will happen next.
 A question mark will appear in the box with an OK button and a Cancel button. If the
user clicks the OK button, true is returned; if he or she clicks the Cancel button, false
is returned.
 This method takes only one argument, the question you will ask the user

var result = confirm(“Continue?”);

APDEV 1 by Vera A. Panaguiton 28


Confirm Dialog Box: Example

APDEV 1 by Vera A. Panaguiton 29


JavaScript FUNCTIONS
A JavaScript function is a block of JavaScript code, that can be executed when asked for,
i.e. a function can be executed when an event occurs.

A function consists of the function keyword followed by the name of the function , a set
of open and close parentheses enclosing an optional parameter list and a body
enclosed in a set of curly braces.
function functionName (parameterList)
{
// body
}
The code inside the function will execute when something invokes the function: when
an event occurs, when it is invoked from JavaScript code, or automatically (self-invoked).

A function uses the return keyword to return


APDEV 1 by Vera A.aPanaguiton
value from a function. 30
EVENTS
These events are normally the result of some user actions. Events are a part of the Document Object Model (DOM)
Level 3 and every HTML element contains a set of events which can trigger JavaScript Code.

APDEV 1 by Vera A. Panaguiton 31


ONCLICK : EXAMPLE 1

APDEV 1 by Vera A. Panaguiton 32


ONCLICK : EXAMPLE 2

APDEV 1 by Vera A. Panaguiton 33


ONCLICK : EXAMPLE 3

Note: To get value from the textbox, use


document.getElementById(“IDNAME”).value;
APDEV 1 by Vera A. Panaguiton 34
JAVASCRIPT OBJECTS
JavaScript sees a Web page as many different objects, such as the browser object, the
document object, and each element of the document as an object; for example, forms,
images, and links are also objects.

JavaScript has a set of its own core objects that allow you to manipulate strings, numbers,
functions, dates, and so on, and JavaScript allows you to create your own objects.

JavaScript supports several types of objects:


1. User-defined objects defined by the
programmer.
2. Core or built-in objects, such as Date,
String, and Number
3. Browser objects, the BOM
4. Document objects, the DOM Figure 2. A hierarchical tree-like structure used to describe components of an object. [4]

APDEV 1 by Vera A. Panaguiton 35


CREATING AN OBJECT WITH A CONSTRUCTOR
JavaScript allows you to create an object in a number of ways. One way is with a constructor.
A constructor is a special kind of function that creates the blueprint for an object.
The new keyword precedes the name of the constructor that will be used to create the
object. By convention, constructor names start with a capital letter to distinguish them from
ordinary functions.
var myNewObject = new Object(argument, argument, ...);

To create the cat object:


var cat = new Object();
JavaScript comes with several built-in constructors, such as:
Object(), Array(), Date(), RegExp(), etc.
var car = new Object();
var friends = new Array(“April", “May", “June");
var holiday = new Date(“December 25, 2020");
var rexp = new RegExp("^[a-zA-Z]");
APDEV 1 by Vera A. Panaguiton 36
PROPERTIES OF OBJECT
 Properties describe the object.
 The object name is followed by a dot and a property.
 The properties are accessible only via their object.

var cat = new Object();


cat.name = “Garfield";
cat.color="yellow";

APDEV 1 by Vera A. Panaguiton 37


METHODS OF OBJECT
 Methods are special functions that object-oriented languages use to describe the
object’s behavior.
 Methods are attached to the object with a dot and are only accessible via that object.
 Methods, like verbs, are action words that perform some operation on the object. The
cat purrs and the dog barks. The cat object may have a method called sleep() or play()
and the dog object may have a method called sit() or stay(), and both of them could
have a method called eat().
 The dot syntax is used to call the methods just as it was used to separate objects from
their properties. When invoked, a set of parentheses are postfixed to the name of the
method. Omitting the parentheses when using a method results in an error.

cat.play();
bird.fly();
dog.fetch("ball");
APDEV 1 by Vera A. Panaguiton 38
OBJECT example

APDEV 1 by Vera A. Panaguiton 39


Classes
 JavaScript ain’t got no class! JavaScript doesn’t have classes
in the traditional sense. It doesn’t have a class keyword.
 A new JavaScript class is defined by creating a simple
function. The name of the function will serve as the class
name for an object, and the function will define its
properties and methods;
 When the function is called with the new keyword, it acts as
a constructor; that is, it builds the new object and then
returns a reference to it. We can say that if you call the
Book() constructor function, it returns a reference to a new
Book object, an instance of the Book class.
 The this keyword is a sort of shorthand reference that keeps
track of the current object. When a function is used as a
constructor, the this keyword is used to set the properties for
the object that was just created. In this way you can create as
many objects as you need and JavaScript this will refer to the
current object. APDEV 1 by Vera A. Panaguiton 40
Inline functions
Rather than naming a function outside the class, an inline or anonymous function can be assigned directly to
a property within the constructor function. (Every instance of the class will have a copy of the function code.)

Base on the example below, the calculate property is assigned an inline or anonymous function. Because it is
part of the definition of the Distance() constructor, only objects of the Distance class will have access to the
method, thereby encapsulating the method.

APDEV 1 by Vera A. Panaguiton 41


Object Literals
Object literals enable you to create objects that support many features without directly invoking a
function. When a function acts as constructor you have to keep track of the order of arguments that will
be passed, and so on. Not so with object literals. They are similar to hashes in other languages using
key/value pairs to represent fields. The fields can be nested.

The basic syntax for an object literal is:


- A colon separates the property name from its value.
- A comma separates each set of name/value pairs from the next set.
- The comma should be omitted from the last name/value pair. Even with nested key/value pairs, the
last key/value pair does not have a comma.
- The entire object is enclosed in curly braces.

The value assigned to a property can be of any data type, including array literals and object literals. An
object literal is both simple and logical, but the biggest short-coming is that the code is not reusable; that
is, you would have to retype the code to use it again within the program, whereas you can use a
constructor function to create multiple instances of an object.
var object = { property1: value, property2: value };
var area =APDEV
{ length: 15, width: 5 };
1 by Vera A. Panaguiton 42
Object Literals: exaple

Note: Make
APDEV 1 by Vera A. Panaguiton sure to check the pairing of your curly 43
braces.
For/in loop
 JavaScript provides the for/in loop, which can be used to iterate through
a list of object properties or array elements.
 The for/in loop reads: for each property in an object (or for each element
in an array) get the name of each property (element), in turn, and for
each of the properties (elements), execute the statements in the block
that follows.
 The for/in loop is a convenient mechanism for looping through the
properties of an object.

APDEV 1 by Vera A. Panaguiton 44


For/in loop example

APDEV 1 by Vera A. Panaguiton 45


WHAT IS DOM?
 DOM stands for Document Object Model. A document object model is a way of conceptualizing a Web page
where the document is represented as a tree structure.
 When an HTML document has been completely loaded, the browser represents it as a tree structure where all
elements in the page are objects.
 When working with forms, JavaScript creates an array of all forms as it encounters them in the document,
where document.forms[0] represents the first form and if there is another form, it is document.forms[1].
Similarly, all images, links, and anchors on the page are stored in a arrays representing their names, such as
document.images and document.links, and so on.
 The elements can be accessed in two ways: by name or by number. If, for example, you name the first form,
“form1”, then you can access it by name (associative array) as document.forms[“form1”] or by numeric index
value (numeric array) as document.forms[0].

Documents contain text, images, forms, links, anchors, and so


on. The most commonly used object is the document object.
Subordinate to the document object are another collection of
objects, its children:
1.The anchors object.
2.The images object.
3.The forms object.
4.The links object. APDEV 1 by Vera A. Panaguiton Figure 3. The document model. [4] 46
Methods of the document Object
Method What It Does
clear() Clears the current document window.
close() Closes the document window for writing.
focus() Brings the document into focus.
getElementById() Returns a reference to the first object with the specified ID.
getElementsByName() Returns a collection of objects with the specified name.
getElementsByTagName() Returns a collection of objects with the specified tag name.
open() Begins a new document, erasing the old one.
write() Writes and appends text into the current document.
writeln() Same as write(), but appends a newline if in a <pre> tag.

APDEV 1 by Vera A. Panaguiton 47


Naming Forms
In naming forms, usually id is used by JavaScript and name is used by PHP.

Normally the id and name attribute should match but this is not always possible. For example, when
creating radio buttons, one name suffices for all the buttons, because only one of the buttons can be
selected, but if you use the id attribute, each id has to be unique as shown here:

APDEV 1 by Vera A. Panaguiton 48


DOM Methods
 DOM methods are actions you can perform (on HTML Elements).
 The DOM Programming Interface is the properties and methods of each object.
 A property is a value that you can get or set (like changing the content of an
HTML element).
 A method is an action you can do (like add or deleting an HTML element).
 For the example below getElementById is a method, while innerHTML is
a property.

APDEV 1 by Vera A. Panaguiton 49


DOM ELEMENTS
Ways in finding HTML Elements:
Finding HTML elements by id – base on the value of the attribute id
Finding HTML elements by tag name – all elements with the same tag
Finding HTML elements by class name
Finding HTML elements by CSS selectors
Finding HTML elements by HTML object collections

<input type=“text” id=“msg”  document.getElementById(“msg")

<p> ... </p> <p> … </p>  document.getElementsByTagName("p");

<input type=“text” class=“msg”  document.getElementByClassName(“msg")

<p class=“msg”> … </p>  document.querySelectorAll("p.msg")

<form><input type=“text” … > … </form>  document.forms[0]


APDEV 1 by Vera A. Panaguiton 50
DOM ELEMENTS Example

APDEV 1 by Vera A. Panaguiton 51


WHAT IS AJAX?
AJAX stands for Asnychronous JavaScript and XML, a term that was coined by Jesse James
Garrett in 2005. It is a technique used to create fast interactivity without having to wait for a
response from the server.

AJAX just uses a combination of:


- A browser built-in XMLHttpRequest object (to request data from a web server)
- JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web server
behind the scenes. This means that it is possible to update parts of a web page, without
reloading the whole page.

Some examples of Ajax applications are Flickr for photo storage and display, Gmail, Google
Suggest, and perhaps the best example, Google Maps.

APDEV 1 by Vera A. Panaguiton 52


WHAT IS jQuery?
 It is a lightweight, "write less, do more", JavaScript library.
 It was created in 2006 by John Resig.
 The purpose of jQuery is to make it much easier to use JavaScript on your website. It takes a lot of
common tasks that require many lines of JavaScript code to accomplish, and wraps them into
methods that you can call with a single line of code.
 It makes things like HTML document traversal and manipulation, event handling, animation, and
Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
 jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM
manipulation.

The jQuery library contains the following features:


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

APDEV 1 by Vera A. Panaguiton 53


Jquery syntax
The jQuery library is a single JavaScript file, just download the file, and you reference it with
the HTML <script> tag. <script src="jquery-3.5.1.min.js"></script> or if your online
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

The jQuery syntax is tailor made for selecting HTML elements and performing some
action on the element(s).

Basic syntax is: $(selector).action()


$ - to define/access jQuery
(selector) - to "query (or find)" HTML elements
action() - to be performed on the element(s)
Examples:
$(this).hide() - hides the current element.
$("p").hide() - hides all <p> elements.
$(".test").hide() - hides all elements with class="test".
$("#test").hide() - hides the element with id="test".
APDEV 1 by Vera A. Panaguiton 54
Document Ready Event
All jQuery methods should be inside a document ready event:

$(document).ready(function(){ <script>
// jQuery methods go here... $(document).ready(function(){
$("button").click(function(){
}); $("#test").hide();
});
shorter method });
</script>
$(function(){
// jQuery methods go here... <p id="test">hide me.</p>
}); <button>Click me</button>

APDEV 1 by Vera A. Panaguiton 55


jQuery Example

APDEV 1 by Vera A. Panaguiton 56


Events
An event represents the precise moment when something happens.
Examples:
moving a mouse over an element
selecting a radio button
clicking on an element

click submit
mouseenter keyup
mouseleave focus
keypress hover

APDEV 1 by Vera A. Panaguiton 57


Event Example 1
Code Snippet

APDEV 1 by Vera A. Panaguiton 58


Event Example 2
Code Snippet

APDEV 1 by Vera A. Panaguiton 59


Event Example 3
Code Snippet

APDEV 1 by Vera A. Panaguiton 60


- ACTIVITY 4 -

APDEV 1 by Vera A. Panaguiton 61


Submit 5 javaScript and 3 jquery files based
on the sample codes.
You can copy the sample codes, just change
their values.
Files don’t mean the .js only.

APDEV 1 by Vera A. Panaguiton 62

You might also like