JavaScript
2020/21 COMP3322 Modern Technologies on WWW
Contents
• JavaScript and its history
• Adding JavaScript
• The JavaScript language
• The Document Object Model (DOM) • Events
• Form Validation
2
Client-Side Scripting
• Let the client compute
3
JavaScript isn’t related to Java
• Although it contains the word Java, 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 JVM installed.
• Conversely, 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.
4
What is JavaScript
• JavaScript runs right inside the browser.
• JavaScript is dynamically typed.
• JavaScript is object-oriented in that almost everything in the language is an object
• The objects in JavaScript are prototype-based rather than class-based, which means that while JavaScript shares some syntactic features of PHP, Java or C#, it is also quite different from those languages.
5
JavaScript History
• JavaScript was introduced by Netscape in their Navigator browser back in 1995.
• JavaScript is in fact an implementation of a standardized scripting language called ECMAScript
• In 1998, ECMAScript 2 was released.
• In 1999, ECMAScript 3 was released.
• Which evolved into what is today’s modern JavaScript.
• ECMAScript 5 was released in 2009 and ECMAScript 2015 (the 6th
edition) was released in 2015.
• At the moment, ECMAScript 2019 (the 10th edition) is the latest release.
Source: Wikipedia ECMAScript
6
Where to place JavaScript?
• JavaScript can be linked to an HTML page in a number of ways. • Inline
• Embedded in the document • Link to an external file
• When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in.
7
Inline JavaScript
• Inline JavaScript refers to add the JavaScript code directly within certain HTML attributes.
• Inline JavaScript is a real maintenance nightmare.
more info
8
Embedded JavaScript
• Embedded JavaScript refers to the practice of placing JavaScript code within a
9
External JavaScript
• JavaScript supports this separation by allowing links to an external file that contains the JavaScript.
• By convention, JavaScript external files have the extension .js.
• You can place an external script reference in or as
you like.
• The script will behave as if it was located exactly where the
62
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, contains everything between the opening <> and closing > tags for this element.
• Can itself contain more elements.
• Element objects implement the DOM Element interface, which has its own set of properties and methods.
63
Element node Object
• Some essential element object properties and methods
Property / Method
Description
attributes
Returns a collection of this element node's attributes.
className
Sets or returns the value of the class attribute of this element.
id
Sets or returns the value of the id attribute of this element.
innerHTML
Sets or returns the markup content of this element.
style
Sets or returns the value of the style attribute of an element (if is a HTMLElement).
tagName
Returns the tag name of an element.
addEventListener()
Attaches an event handler to this element.
getAttribute() setAttribute() removeAttribute()
Returns / sets / removes the specified attribute value of this element.
64
Accessing Element Attributes
Welcome Guys!
Hello! I am Anthony and this is my course simple home page.
To access the course's Moodle site, please visit
here.
var lnk = document.links[0].href;
var Alnk = document.getElementsByTagName("a")[0].getAttribute('href');
65
Adding Content
var elm = document.querySelector('p').innerHTML; document.querySelector('p').innerHTML =
elm + "
My phone no. is: 2859 7073
"
66
Changing Element Styles
document.getElementById('header').style.backgroundColor = 'blue'; document.querySelector('p').style.color = "red"; document.querySelector('a').style.color = "green"; document.getElementsByTagName('h1')[0].style.width = "250px";
67
Event Handling
Events
• Events are actions or occurrences that happen in the system.
• When system detects an event, it fires a signal of some kind/form and
some action can be automatically taken to handle the event.
• In the case of the Web, there are many types of events: • The user is clicking the mouse over a certain element.
• Thecursorishoveringoveranelement.
• The user is pressing a key on the keyboard.
• Theuserisresizingorclosingthebrowserwindow. • A web page is loaded completely.
• An error occurred.
69
Event Handlers
• Each available event has an event handler, which is a block of code (usually a JavaScript function) that will be run when the event fires.
window.onclick = function() {
/* Any code placed here will run when the user
clicks anything within the browser window */
};
• When such a block of code is defined to be run in response to an event firing, we say we are registering an event handler.
70
Common Web Events
• Mouse events
Attribute Description
onclick The mouse clicks an element.
ondblclick Double-click on an element.
onmousedown A mouse button is pressed down on an element.
onmousemove The mouse pointer is moving while it is over an element.
onmouseout The mouse pointer moves out of an element.
onmouseover The mouse pointer moves over an element.
onmouseup A mouse button is released over an element.
71
Common Web Events
• Window events
Attribute
Description
onerror
An error occurs when the document or an image loads.
onload A page (including all images) is finished loading.
onresize
Fires when the browser window is resized.
onunload When another page is loaded or when the browser window is closed.
Attribute Description
onkeypress When a user presses a key. (Deprecated)
onkeydown When a user is pressing a key.
onkeyup When a user releases a key.
• Keyboard events
To get more information on HTML events, please visit: https://www.w3schools.com/tags/ref_eventattributes.asp
72
Registering Event Handlers
• There are three common methods for applying event handlers to elements within web pages:
• As an HTML attribute
• As a method attached to the element • Using addEventListener( )
73
As an HTML attribute
• You can specify the function to be run in an attribute in the markup.
• They are considered bad practice.
• It is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse.
• Could lead to a maintenance nightmare. https://i.cs.hku.hk/~atctam/c3322/JS/Event-demo1.html
74
https://i.cs.hku.hk/~atctam/c3322/JS/Event-demo2.html
As a Method
• We can keep the code strictly within the
• This approach has the benefit of simplicity and ease of
maintenance, but has a major drawback.
• We can bind only one event handler to an item at a time with this method.
75
https://i.cs.hku.hk/~atctam/c3322/JS/Event-demo3.html
Using addEventListener()
• Inside the addEventListener() function, we specify two parameters: • the name of the event, e.g, click
• the code of the handler function
• This approach allows us to keep the logic within the scripts and allows us to perform multiple bindings on a single object.
• Both handlers would run when the event occurs.
76
https://i.cs.hku.hk/~atctam/c3322/JS/Event-demo4.html
removeEventListener()
• We can remove event handler code using removeEventListener()
• Same as addEventListener(), we specify two parameters: • the name of the event
• the handler function
77
Event Object
• No matter which type of event we encounter, they are just another type of DOM objects and the event handlers associated with them can access and manipulate them.
• Typically we see the events passed to the function handler as a parameter named e, evt, or event.
function someHandler(e) {
// e is the event object, which represents the event that triggered this handler.
}
78
https://i.cs.hku.hk/~atctam/c3322/JS/Event-demo5.html
Event Propagation – Bubbling
• When an event is fired on an element:
• The browser first checks whether that element has an event handler on that
event, and runs it if so.
• Afterwards, it checks the next immediate ancestor element and does the same thing, then the next ancestor, and so on until it reaches the element.
• In that case, one user action can trigger multiple event handlers in action.
• This is the default behavior of modern browsers. • The exact opposite behavior is called Capturing.
79
https://i.cs.hku.hk/~atctam/c3322/JS/Event-demo6.html
Event Propagation – Capturing
• The browser checks to see if the onclicked element's outer-most ancestor () has an onclick event handler registered for capturing, and runs it if so.
• Then it moves on to the next element inside and does the same thing, then the next one, and so on until it reaches the onclicked element.
• To use the Capturing behavior, we set the third argument of the addEventListener() to true, which is set to false by default.
element.addEventListener(event, function, useCapture) addEventListener('click', bgChange, true)
80
Event Object
• Some essential properties and methods of the event object
https://developer.mozilla.org/en-US/docs/Web/API/Event
Property / Method
Description
bubbles
Indicates whether the event bubbles property is enable.
cancelable
Returns a Boolean value indicating whether or not an event is a cancelable event. The event is cancelable if it is possible to prevent the events default action to be happened.
currentTarget
Refers to the element to which the current event handler is attached to, as opposed to target which identifies the element on which the event occurred.
defaultPrevented
Returns whether or not the preventDefault() method was called for the event.
target
Returns the element that triggered the event.
type
Returns the name of the event.
preventDefault()
Instructs the system to cancel the default action if the event is cancelable.
stopPropagation()
Prevents further propagation of an event during event propagation.
81
Form Validation
Validating Forms – Client-Side
• Client-side validation is validation that occurs in the browser, before the data has been submitted to the server.
• Doing that on the client side will reduce the number of incorrect submissions, thereby reducing server load.
• There are a number of common validation activities including email validation, number validation, and data validation.
• With HTML5, form validation becomes much easy.
• This generally does not require JavaScript.
• Most modern browsers support this feature.
• However, the behavior is more or less depended on the browsers.
• Using JavaScript, we can have more control and customization of the validation in the client-side.
83
HTML5 Form elements (Recap)
Text Email Textarea
Password
Checkbox
Select
URL
Date
84
HTML Built-in Validation
• Most of the input are text contents, numbers, strings with special patterns, is required or not, etc.
• HTML uses validation attributes on form elements to validate most user input.
• With the attributes, we can specify rules such as:
maxlength
• A required field is still empty.
• Exceed the maximum length.
• The number is too large or small. min max • The input is not a valid email address or URL.
• The input does not match the required pattern.
pattern
required minlength
85
Example
Account Registration Form
Specifies that an input field must be filled out before submitting the form
The min & max attributes specify the minimum and
86
Example
HTML
With 10 numerical characters starting with '3015'
Account Registration Form
Must be a number with 1 or more digit
87
HTML Built-in Validation
• If the input data doesn’t satisfy the prescribed rule, it is considered invalid; otherwise, it is considered valid.
• With the valid / invalid status, we can make use of the built-in CSS pseudo-class for the visualization.
• When an element XX is valid:
• This matches the XX:valid styling rule, the system will apply the specific style to that
valid element XX.
• When an element XX is invalid:
• This matches the XX:invalid styling rule and the specific style will be applied.
• Thebrowserwillblocktheformfromsubmissionanddisplayanerrormessage.
88
Example
If the input element is in invalid status, sets the border to dashed red color
CSS
If the input element is in valid status, sets the border to black color
https://i.cs.hku.hk/~atctam/c3322/JS/demo-form-val1.html
89
Customization
• HTML5 provides another API called constraint validation.
• The purpose is for us to check the state of a form element; given
the state, we can take appropriate actions.
• It’s also possible to change the text of the error message.
90
Constraint Validation API
https://developer.mozilla.org/en-US/docs/Web/API/Constraint_validation
Property / Method
Description
validity
A ValidityState object describing the validity state of the element.
validity.patternMismatch
Set to true, if an element's value does not match its pattern attribute.
validity.rangeOverflow
Set to true, if an element's value is greater than its max attribute.
validity.rangeUnderflow
Set to true, if an element's value is less than its min attribute.
validity.tooLong
Set to true, if an element's value exceeds its maxLength attribute.
validity.valueMissing
Set to true, if an element (with a required attribute) has no value.
checkValidity()
Returns true if an input element contains valid data.
setCustomValidity()
Adds a custom error message to the element
91
JavaScript
Example
When user enters something to the input element
This function checks whether the value matches the specific pattern
92
https://i.cs.hku.hk/~atctam/c3322/JS/demo-form-val2.html
JavaScript
Example
93
Readings
• MDN Web Docs
• JavaScript First Steps
• https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps • JavaScript Building Blocks
• https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks • Manipulating Documents
• https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client- side_web_APIs/Manipulating_documents
94
References
• Some slides are borrowed from the book:
• Fundamentals of Web Development by Randy Connolly and Ricardo Hoar,
published by Pearson. • W3Schools.com
• JavaScript Tutorial
• https://www.w3schools.com/js/default.asp
• JavaScript Info
• https://javascript.info/
95