Session 5,6
11/12/2024 1
Module Overview
• Overview of JavaScript
• Introduction to the Document Object Model
• Introduction to jQuery
Lesson 1: Overview of JavaScript
• What is JavaScript?
• JavaScript Syntax
• Variables, Data Types, and Operators
• Functions
• Conditional Statements
• Looping Statements
• Using Object Types
• Defining Arrays of Objects by Using JSON
What is JavaScript?
• JavaScript is a programming language that
supports:
Operators
Conditional
Variables Statements
Functions Objects
and Loops
• Use JavaScript with the Document Object Model
and Browser Object Model to make web pages
dynamic.
• Use the AJAX API to make asynchronous requests
to a web server.
JavaScript Syntax
• A JavaScript statement represents a line of code to
be run
• Terminate statements with a semicolon
var thisVariable = 3;
counter = counter + 1;
GoDoThisThing();
document.write("An incredibly really \
very long greeting to the world");
• Use comments to add notes to your scripts
document.write("I'm learning JavaScript"); // display a message
/* You can use a multi-line comment
to add more information */
Variables, Data Types, and Operators
• Use var to declare variables
var answer = 3;
var actuallyAsString = "42";
• JavaScript has three simple types
• String, Number, and Boolean
• Variables can also be undefined or null
var noValue; // noValue has the value undefined
var nullValue = null; // null is different to undefined
• JavaScript supports many operators
• Arithmetic, assignment, comparison, Boolean,
conditional, and string
Functions
• Functions are named blocks of reusable code:
function aName( argument1, argument2, …, argumentN )
{
statement1;
statement2;
…
statementN;
}
• Arguments are only accessible inside the function
• A function can return a value
• A function can also declare local variables
• Global variables defined outside of a function are
available to all functions in scripts referenced by a page
Conditional Statements
• JavaScript provides two conditional constructs
• if: if (TotalAmountPaid > AdvancePaid) {
GenerateNewInvoice();
} else {
WishGuestAPleasantJourney();
}
var RoomRate;
switch (typeOfRoom) {
case "Suite":
• switch: RoomRate = 500;
break;
case "King":
RoomRate = 400;
break;
default:
RoomRate = 300;
}
Looping Statements
• JavaScript provides three loop constructs
while (GuestIsStillCheckedIn())
• while: {
numberOfNightsStay += 1;
}
do {
• do while: eatARoundOfToast();
} while (StillHungry())
for (var i=0; i<10; i++) {
• for: plumpUpAPillow();
}
Using Object Types
• JavaScript has a number of built-in object types:
• String, Date, Array, RegExp
var seasonsArray = ["Spring", "Summer", "Autumn", "Winter"];
…
var autumnLocation = seasonsArray.indexOf("Autumn");
var re = new RegExp("[dh]og");
if (re.test("dog")) {...}
• JavaScript also provides singleton types providing
useful functionality:
• Math, Global
Defining Arrays of Objects by Using JSON
• JSON is a format for serializing objects:
var attendees = [
{
"name": “Eric Gruber",
"currentTrack": "1"
},
{
"name": “Martin Weber",
"currentTrack": “2"
}
]
• JavaScript provides APIs for serializing and parsing
JSON data
Lesson 2: Introduction to the Document Object
Model
• The Document Object Model
• Finding Elements in the DOM
• Adding, Removing, and Manipulating Objects in the DOM
• Handling Events in the DOM
The Document Object Model
• The DOM provides a programmatic API for
controlling a browser and accessing the contents
of a web page:
• Finding and setting the values of elements on a page
• Handling events for controls on a page
• Modifying the styles associated with elements
• Serializing and deserializing a page as an XML document
• Validating and updating web pages
Finding Elements in the DOM
• Given the following form:
<form name="contactForm">
<input type="text" name="nameBox" id="nameBoxId" />
</form>
• You can reference the form by using:
document.forms[0] // forms is a zero-based array
document.forms["contactForm"]
document.forms.contactForm
document.contactForm
• You can reference the nameBox text box by using:
document.forms.contactForm.elements[0]
document.forms.contactForm.elements["nameBox"]
document.forms.contactForm.nameBox
document.contactForm.nameBox
document.getElementById("nameBoxId")
Adding, Removing, and Manipulating Objects in the
DOM
To modify an element on a page:
1. Create a new object containing the new data.
2. Find the parent element that should contain the
new data.
3. Append, insert, or replace the data in the
element with the new data.
To remove an element or attribute:
1. Find the parent element.
2. Use removeChild or removeAttribute to
remove the data.
Handling Events in the DOM
• The DOM defines events that can be triggered by the
browser or by the user
• Many HTML elements define callbacks that run when an
event occurs:
var helpIcon = document.getElementById("helpIcon");
document.images.helpIcon.onmouseover =
function() { window.alert('Some help text'); };
• You can also define event listeners that run when an event
fires:
• This is useful if the same event needs to trigger multiple actions
helpIcon.addEventListener("mouseover",
function() { window.alert('Some help text'); }, false);
• To remove an event listener:
helpIcon.removeEventListener("mouseover", ShowHelpText, false);
Lesson 3: Introduction to jQuery
• The jQuery Library
• Demonstration: Adding jQuery to a Web Project
• Selecting Elements and Traversing the DOM by Using jQuery
• Adding, Removing, and Modifying Elements by Using jQuery
• Handling Control Events by Using jQuery
• Demonstration: Displaying Data and Handling Events by Using JavaScript
The jQuery Library
• jQuery provides portability for JavaScript code,
enabling you to easily build cross-browser web
applications:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Example</title>
<script type="text/javascript" src="Scripts/jquery-1.8.0.min.js">
</script>
</head>
<body>
…
<script type="text/javascript">
$(document).ready(function () {
// some code
});
</script>
</body>
</html>
Demonstration: Adding jQuery to a Web Project
In this demonstration, you will see how to:
• Add jQuery to a Project by Using nuGet
• Enable jQuery Intellisense
Selecting Elements and Traversing the DOM by
Using jQuery
• jQuery uses the same selector syntax as CSS
<script type="text/javascript">
$(document).ready(function () {
$("h2").each(function () {
this.style.color = “red";
});
});
</script>
• jQuery provides additional functions for traversing
and filtering elements
Adding, Removing, and Modifying Elements by
Using jQuery
• Use the selector function to specify the elements
to change or remove
• Common methods include:
• addClass $("p").addClass("strike");
• append $("ul").append("<li>New item</li>");
• detach $(#Warning").detach();
• html $("h1").html("<hgroup>…</hgroup>");
• replaceWith $(#Warning").replaceWith("<p>Panic over!</p>");
• val $("input[type=text").val();
Handling Control Events by Using jQuery
• Use the jQuery selector function to find the item
that raises the event
• Use the bind method (or a jQuery shortcut) to
bind the event handler to the event
<script type="text/javascript">
$(document).ready(function () {
$("#submit").click(
function () {
var userName = $("#NameBox").val();
$("#thankYouArea").replaceWith(
"<p>Thank you " + userName + "</p>");
})
});
</script>
Demonstration: Displaying Data and Handling Events by Using JavaScript
In this demonstration, you will learn about the tasks
that you will perform in the lab for this module.
Lab: Displaying Data and Handling Events by Using
JavaScript.
• Exercise 1: Displaying Data Programmatically
• Exercise 2: Handling Events
Lab Scenario
The conference being organized by ContosoConf
consists of a number of sessions that are
organized into tracks. A track groups sessions of
related technologies, and conference attendees
can view the sessions in a track to determine
which ones may be of most interest to them.
To assist conference attendees, you have been
asked to create a Schedule page for the
ContosoConf website listing the tracks and
sessions for the conference.
Module Review and Takeaways
• Review Question(s)
11/12/2024 28
Module Overview
• Writing Well-Structured JavaScript Code
• Creating Custom Objects
• Extending Objects
Lesson 1: Writing Well-Structured JavaScript Code
• Scoping and Hoisting
• Managing the Global Namespace
• Singleton Objects and Global Functions in JavaScript
Scoping and Hoisting
• JavaScript variables have one of two scopes:
• Global scope
• Local scope within a function
• JavaScript does not support block scope
• If you declare a variable inside a block, it is hoisted to
function scope
var num = 7;
function demonstrateScopingAndHoisting() {
if (true) {
var num = 42;
}
alert("The value of num is " + num); // Displays 42, not 7.
}
Managing the Global Namespace
• Global name clashes can be problematic in
JavaScript
• Your global variables might conflict with other global
variables elsewhere in the web application
• JavaScript provides several mechanisms to avoid
global name clashes
• Immediate functions
• Namespaces
• Strict mode
Singleton Objects and Global Functions in JavaScript
• JavaScript defines several singleton objects, such
as:
• Math
• JSON
• JavaScript also defines global functions, such as:
• parseInt()
• parseFloat()
• isNan()
Lesson 2: Creating Custom Objects
• Creating Simple Objects
• Using Object Literal Notation
• Using Constructors
• Using Prototypes
• Using the Object.create Method
Creating Simple Objects
• There are several ways to create new objects in
JavaScript:
var employee1 = new Object();
var employee2 = {};
• You can define properties and methods on an
object:
var employee1 = {};
employee1.name = "John Smith";
employee1.age = 21;
employee1.salary = 10000;
employee1.payRise = function(amount) {
// Inside a method, "this" means the current object.
this.salary += amount;
return this.salary;
}
Using Object Literal Notation
• Object literal notation provides a shorthand way
to create new objects and assign properties and
methods:
var employee2 = {
name: "Mary Jones",
age: 42,
salary: 20000,
payRise: function(amount) {
this.salary += amount;
return this.salary;
},
displayDetails: function() {
alert(this.name + " is " + this.age + " and earns " + this.salary);
}
};
Using Constructors
• Constructor functions define the shape of objects
• They create and assign properties for the target object
• The target object is referenced by the this keyword
var Account = function (id, name) {
this.id = id;
this.name = name;
this.balance = 0;
this.numTransactions = 0;
};
• Use the constructor function to create new objects
with the specified properties:
var acc1 = new Account(1, "John");
var acc2 = new Account(2, "Mary");
Using Prototypes
• All objects created by using a constructor function
have their own copy of the properties defined by
the constructor
• All JavaScript objects, including constructors, have a
special property named prototype
• Use the prototype to share function definitions between
objects:
Account.prototype = {
deposit: function(amount) {
this.balance += amount;
this.numTransactions++;
},
// Plus other methods…
};
Using the Object.create Method
• Use Object.create() to create an object based on
existing prototype
• Pass in a prototype object
• Optionally pass in a properties object that specifies
additional properties to add to the new object
var obj1 = Object.create(prototypeObject, propertiesObject);
• The new object has access to all the properties
defined in the specified prototype
• It forms the basis of the approach used by many
JavaScript developers to implement inheritance.
Lesson 3: Extending Objects
• Implementing Encapsulation
• Implementing Inheritance by Chaining Prototypes
• Adding Functionality to Existing Objects
• Demonstration: Refining Code for Maintainability and Extensibility
Implementing Encapsulation
• To define private members for an object, declare
variables in the constructor and omit the this keyword
• To define public accessor functions for an object,
declare methods in the constructor and include the this
keyword
var Person = function(name, age)
{
// Private properties.
var _name, _age;
// Public accessor functions.
this.getName = function()
{
return _name;
}
…
}
Implementing Inheritance by Chaining Prototypes
• Define the base constructor and prototype
• Define the derived constructor
• Set the prototype property of the derived
constructor to an instance of the base object
prototype
Person Person.
Prototype
constructor
prototype constructor
Student
Adding Functionality to Existing Objects
• Get the prototype for an object
• Assign a new property to the object
var Point = function(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.moveBy = function(deltaX, deltaY) { … }
Point.prototype.moveTo = function(otherPoint) { … }
var p1= new Point(100, 200);
p1.moveBy(10, 20);
p1.moveTo(anotherPoint);
• Use the apply method to resolve references to
this in generic functions
Demonstration: Refining Code for Maintainability
and Extensibility
In this demonstration, you will learn about the tasks
that you will perform in the lab for this module.
Lab: Refining Code for Maintainability and
Extensibility
• Exercise 1: Object Inheritance
• Exercise 2: Refactoring JavaScript Code to Use Objects
Lab Scenario
The existing JavaScript code for the ContosoConf website
has been written without much high-level structure or
organization. While this approach is fine for small pieces of
code, it will not scale up for a larger project. An
unstructured collection of functions and variables
scattered throughout a JavaScript file can quickly become
unmaintainable.
Before implementing more website features by using
JavaScript, you decide to refactor the existing code to
introduce better organizational practices. The resulting
code will be more maintainable and provide a good
pattern for implementing future website features.
Module Review and Takeaways
• Review Question(s)