JavaScript
The HTML DOM , javascript Forms
Java Script Operators
Arithmetic operators Assignment Operators
Operator Description Operator Example Same As
+ Addition = x=y x=y
- Subtraction += x += y x=x+y
* Multiplication -= x -= y x=x-y
** Exponentiation (ES2016) *= x *= y x=x*y
/ Division /= x /= y x=x/y
% Modulus (Division Remainder) %= x %= y x=x%y
++ Increment **= x **= y x = x ** y
-- Decrement
String Oprators :
The + operator can also be used to add (concatenate) strings.
Example:
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;
Comparison operators Bitwise Operators
Operator Description
Operator Description Example Same as Result Decimal
== equal to
=== equal value and equal type & AND 5&1 0101 & 0001 1
0001
!= not equal | OR 5|1 0101 | 0101 5
!== not equal value or not equal type 0001
> greater than ~ NOT ~5 ~0101 1010 10
^ XOR 5^1 0101 ^ 0100 4
< less than
0001
>= greater than or equal to << Zero fill left shift 5 << 1 0101 << 1 1010 10
<= less than or equal to
? ternary operator >> Signed right shift 5 >> 1 0101 >> 1 0010 2
Logical operators >>> Zero fill right shift 5 >>> 1 0101 >>> 1 0010 2
Operator Description
&& logical and
|| logical or
! logical not
Introduction
• JavaScript is the programming language of the Web.
• All JavaScript identifiers are case sensitive.
• With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
• The HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates a Document Object Model of the page.
• Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a document.“
• DOM standard is separated into 3 different parts:
• Core DOM - standard model for all document types
• XML DOM - standard model for XML documents
• HTML DOM - standard model for HTML documents
• The HTML DOM model is constructed as a tree of Objects:
• 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 Document Object
• The document object represents your web page.
• If you want to access any element in an HTML page, you always start with accessing the document object.
• HTML DOM methods are actions you can perform (on HTML Elements).
• HTML DOM properties are values (of HTML Elements) that you can set or change.
• In the DOM, all HTML elements are defined as objects.
• The 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).
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
• The getElementById Method
• The most common way to access an HTML element is to use the id of the element.
• In the example above the getElementById method used id="demo" to find the element.
• The innerHTML Property
• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML elements.
• (The innerHTML property can be used to get or change any HTML element, including <html> and <body>.
)
Finding HTML Elements
• We need to find elements if you want to manipulate
HTML elements with JavaScript.
• There are several ways to do this:
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections
• Finding HTML Element by Id
• The easiest way to find an HTML element in the DOM, is by using the element id.
• var myElement = [Link]("intro");
• If the element is found, the method will return the element as an object (in myElement).
• If the element is not found, myElement will contain null.
• Finding HTML Elements by Tag Name
• var x = [Link]("p");
• Finding HTML Elements by Class Name
• If you want to find all HTML elements with the same class name, use getElementsByClassName().
• This example returns a list of all elements with class="intro".
• var x = [Link]("intro");
• Finding HTML Elements by CSS Selectors
• If you want to find all HTML elements that match a specified CSS selector (id, class names, types,
attributes, values of attributes, etc), use the querySelectorAll() method.
• The querySelectorAll() method returns all elements in the document that matches a specified CSS
selector(s), as a static NodeList object.
• The NodeList object represents a collection of nodes. The nodes can be accessed by index
numbers. The index starts at 0.
• This example returns a list of all <p> elements with class="intro"
• var x = [Link]("[Link]");
Finding HTML Elements by HTML Object Collections
This example finds the form element with id="frm1", in the forms collection, and displays all element values:
<form id="frm1" action="/action_page.php">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br><br>
<input type="submit" value="Submit">
</form>
<p>Click "Try it" to display the value of each element in the form.</p>
<button it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = [Link]["frm1"];
var text = "";
var i;
for (i = 0; i < [Link] ;i++) {
text += [Link][i].value + "<br>";
}
[Link]("demo").innerHTML = text;
}
</script>
• The following HTML objects (and object collections) are also accessible:
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
Changing HTML
• Changing the HTML Output Stream
• JavaScript can create dynamic HTML content:
• In JavaScript, [Link]() can be used to write directly to the HTML output stream:
• <!DOCTYPE html>
<html>
<body>
<script>
[Link](Date());
</script>
</body>
</html>
• Changing HTML Content
• The easiest way to modify the content of an HTML element is by using the innerHTML property.
• To change the content of an HTML element, use this syntax:
• [Link](id).innerHTML = new HTML
• This example changes the content of a <p> element:
<p id="p1">Hello World!</p>
<script>
[Link]("p1").innerHTML = "New text!";
</script>
• Changing the Value of an Attribute
• To change the value of an HTML attribute, use this syntax:
• [Link](id).attribute = new value
• This example changes the value of the src attribute of an <img> element:
<img id="myImage" src="[Link]">
<script>
[Link]("myImage").src = "[Link]";
</script>
Changing CSS
• Changing HTML Style
• To change the style of an HTML element, use this syntax:
• [Link](id).[Link] = new style
<p id="p2">Hello World!</p>
<script>
[Link]("p2").[Link] = "blue";
</script>
• Using Events
• The HTML DOM allows you to execute code when an event occurs.
• Events are generated by the browser when "things happen" to HTML elements:
• An element is clicked on
• The page has loaded
• Input fields are changed
<h1 id="id1">My Heading 1</h1>
<button type="button"
= 'red'">
Click Me!</button>
JavaScript HTML DOM Animation
• Create an Animation Container
• All animations should be relative to a container element.
<div id ="container">
<div id ="animate">My animation will go here</div>
</div>
• Style the Elements
• The container element should be created with style = "position: relative".
• The animation element should be created with style = "position: absolute".
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
• Animation Code
• JavaScript animations are done by programming gradual changes in an element's style.
• The changes are called by a timer. When the timer interval is small, the animation looks continuous.
• The basic code is:
var id = setInterval(frame, 5);
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
• The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
• The setInterval() method will continue calling the function until clearInterval() is called, or the window is
closed.
• The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
• Tip: 1000 ms = 1 second.
• Tip: To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.
<script>
<html>
var id = null;
<style>
function myMove() {
#container {
var elem = [Link]("animate");
width: 400px;
var pos = 0;
height: 400px;
clearInterval(id);
position: relative;
id = setInterval(frame, 5);
background:grey;
function frame() {
}
if (pos == 350) {
#animate {
clearInterval(id);
width: 50px;
} else {
height: 50px;
pos++;
position: absolute;
[Link] = pos + "px";
background-color: red;
[Link] = pos + "px";
}
}
</style>
}
<body>
}
<p><button Me</button></p>
</script>
<div id ="container">
</body>
<div id ="animate"></div>
</html>
</div>
JavaScript HTML DOM Events
• A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
• To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
• >• Examples of HTML events:
• When a user clicks the mouse
• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key
• HTML Event Attributes
• To assign events to HTML elements you can use event attributes.
<h1 id="one" on this text!</h1>
<script>
function changeText() {
[Link] = "Ooops!";
}
</script>
• Assign Events Using the HTML DOM Attribute (mouse Attribute
(form events)
• The HTML DOM allows you to assign events to HTML elements using JavaScript: events)
onclick onblur
<button id="myBtn">Try it</button> onchange
ondblclick
<p id="demo"></p> onmousedown
oncontextmenu
<script> onmousemove
onfocus
oninput
[Link]("myBtn"). onmouseout oninvalid
function displayDate() { onmouseover onreset
[Link]("demo").innerHTML = Date(); onmouseup onsearch
onmousewheel
} onselect
onwheel onsubmit
</script>
The onload and onunload Events
• The onload and onunload events are triggered when the user enters or leaves the page.
• The onload event can be used to check the visitor's browser type and browser version, and load the proper
version of the web page based on the information.
• The onload and onunload events can be used to deal with cookies.
<img src="[Link]" width="100" height="132">
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
• The onchange Event
• The onchange event is often used in combination with validation of input fields.
• Below is an example of how to use the onchange. The upperCase() function will be called when a user
changes the content of an input field.
<head>
<script>
function myFunction() {
var x = [Link]("fname");
[Link] = [Link]();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" >
• The onmouseover and onmouseout Events
• The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or
out of, an HTML element:
<html>
<body>
<div id="div1"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver() {
[Link]("div1").innerHTML = "Thank You"
}
function mOut() {
[Link]("div1").innerHTML = "Mouse Over Me"
}
</script>
</body>
</html>
DOM Event Listner
• The addEventListener() method
• The addEventListener() method attaches an event handler to an element without overwriting existing
event handlers.
• You can add many event handlers of the same type to one element, i.e two "click" events.
• You can add event listeners to any DOM object not only HTML elements. i.e the window object.
• The addEventListener() method makes it easier to control how the event reacts to bubbling.
• When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better
readability and allows you to add event listeners even when you do not control the HTML markup.
• You can easily remove an event listener by using the removeEventListener() method.
• Syntax : [Link](event, function, useCapture);
• The first parameter is the type of the event (like "click" or "mousedown")
• The second parameter is the function we want to call when the event occurs.
• The third parameter is a boolean value specifying whether to use event bubbling or event capturing.
This parameter is optional.
• Bubbling:When an event happens on an element, it first runs the handlers on it, then on its parent,
then all the way up on other ancestors.
• In bubbling the inner most element's event is handled first and then the outer
• Capturing:Event capturing is the event starts from top element to the target element. It is the
opposite of Event bubbling
• The default value is false, which will use the bubbling propagation, when the value is set to true, the event
uses the capturing propagation.
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
var x = [Link]("myBtn");
[Link]("mouseover", myFunction);
[Link]("click", mySecondFunction);
[Link]("mouseout", myThirdFunction);
function myFunction() {
[Link]("demo").innerHTML += "Moused over!<br>";
}
function mySecondFunction() {
[Link]("demo").innerHTML += "Clicked!<br>";
}
function myThirdFunction() {
[Link]("demo").innerHTML += "Moused out!<br>";
}
</script>
JavaScript Forms
• JavaScript Form Validation
• HTML form validation can be done by JavaScript.
<head>
<script>
function validateForm() {
var x = [Link]["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}}
</script> </head>
<body>
<form name="myForm" action="[Link]" validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
JavaScript Can Validate Numeric Input
• The isNaN() function determines whether a value is an illegal number (Not-a-Number).
• This function returns true if the value equates to NaN. Otherwise it returns false.
<p>Please input a number between 1 and 10:</p>
<input type=text id="numb">
<button type="button" > <p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = [Link]("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
[Link]("demo").innerHTML = text;
}
</script>
• Automatic HTML Form Validation
• HTML form validation can be performed automatically by the browser:
• If a form field (fname) is empty, the required attribute prevents this form from being submitted:
<input type="text" name="fname" required>
<input type="submit" value="Submit">
• Data Validation
• Data validation is the process of ensuring that user input is clean, correct, and useful.
• Typical validation tasks are:
• has the user filled in all required fields?
• has the user entered a valid date?
• has the user entered text in a numeric field?
• Most often, the purpose of data validation is to ensure correct user input.
• Validation can be defined by many different methods, and deployed in many different ways.
• Server side validation is performed by a web server, after input has been sent to the server.
• Client side validation is performed by a web browser, before input is sent to a web server.
• HTML Constraint Validation
• HTML5 introduced a new HTML validation concept called constraint validation.
• HTML constraint validation is based on:
• Constraint validation HTML Input Attributes
• Constraint validation CSS Pseudo Selectors
• Constraint validation DOM Properties and Methods
Constraint Validation HTML Input Attributes
Attribute Description
disabled Specifies that the input element should be
disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element
Constraint Validation CSS Pseudo Selectors
Selector Description
:disabled Selects input elements with the "disabled" attribute
specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute
specified
:required Selects input elements with the "required" attribute
specified
:valid Selects input elements with valid values
JavaScript Validation API
Constraint Validation DOM Methods
Property Description
checkValidity() Returns true if an input element contains valid data.
setCustomValidity() Sets the validationMessage property of an input element.
• Constrint Validation:
• The core of constraint validation is an algorithm browsers run when a form is submitted to
determine its validity. To make this determination, the algorithm utilizes new HTML5
attributes min, max, step, pattern, and required as well as existing attributes maxlength and type.
• checkValidity() :
• The checkValidity method on a form element node (e.g. input, select, textarea) returns true if the
element contains valid data.
• setCustomValidity():
• The setCustomValidity method changes the validationMessage property as well as allows you to add
custom validation rules.
• Checkvalidity():
<input id="id1" type="number" min="10" max="30" required>
<button >
<p>If the number is less than 100 or greater than 300, an error message will be displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = [Link]("id1");
if (![Link]()) {
[Link]("demo").innerHTML = [Link];
} else {
[Link]("demo").innerHTML = "Input OK";
}
}
</script>
• setCustomValidity() :
<html>
<body>
<form>
<label for="pass">Enter Password:</label>
<input id="pass" type="password" required>
<button type="submit" Submit</button>
</form>
<script>
function checkPassword() {
var pwd = [Link]("#pass");
if ([Link] != "WebProgramming") {
[Link]("Wrong. It's 'WebProgramming'.");
} else {
[Link](""); // be sure to leave this empty!
alert("Correct!");
}
}
</script>
</body>
</html>
Constraint Validation DOM Properties
Property Description
validity Contains boolean properties related to the validity of an input element.
validationMessage Contains the message a browser will display when the validity is false.
willValidate Indicates if an input element will be validated.
The validity property of an input element contains a number of properties related to the validity of data:
Property Description
customError Set to true, if a custom validity message is set.
patternMismatch Set to true, if an element's value does not match its pattern attribute.
rangeOverflow Set to true, if an element's value is greater than its max attribute.
rangeUnderflow Set to true, if an element's value is less than its min attribute.
stepMismatch Set to true, if an element's value is invalid per its step attribute.
tooLong Set to true, if an element's value exceeds its maxLength attribute.
typeMismatch Set to true, if an element's value is invalid per its type attribute.
valueMissing Set to true, if an element (with a required attribute) has no value.
valid Set to true, if an element's value is valid.
• Some practice examples: customError
<html>
<head>
</head>
<body>
<form>
<input type=submit value="submit">
<input type= text id="t1" > <input type=text id="t2" > <script>
function custError(){
var x1= [Link]('t1').[Link]; //false
[Link]('t2').setCustomValidity('Invalid');
var x2=[Link]('t2').[Link]; //true
[Link]('res').innerHTML= "t1:" + x1 +"<br>"+"t2:"+x2
}
</script>
<p id="res"></p>
</form>
</body>
</html>
Range overflow
<html>
<body>
<p>Enter a number and click OK:</p>
<input id="id1" type="number" max="100">
<button >
<p>If the number is greater than 100 (the input's max attribute), an error message will be displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var txt = "";
if ([Link]("id1").[Link]) {
txt = "Value too large";
} else {
txt = "Input OK";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>
PatternMismatch
<body><form>
<input type=text id="foo" pattern="[0-9]{4}" ><p id="demo"></p>
<script>
function fun(){
var abc="";
if ([Link]('foo').[Link])
{ abc="please check the pattern"; }
else { abc="all ok"; }
[Link]("demo").innerHTML = abc;}
</script>
</form>
</body>
validationMeassage
• The validationMessage property of a DOM node contains the message the browser displays to the user when a node's validity is
checked and fails.
• The browser provides a default localized message for this property. If the DOM node is not a candidate for constraint validation or
if the node contains valid data validationMessage will be set to an empty string.
<form>
<input type="text" id="txt" required />
<input type=submit value="submit">
<script>
[Link]('txt').validationMessage;
//Chrome --> 'Please fill out this field.'
//Firefox --> 'Please fill out this field.'
//Safari --> 'value missing'
//IE10 --> 'This is a required field.'
//Opera --> ''
</script>
willValidate
• The willValidate property indicates whether the node is a candidate for constraint
validation. For submittable elements this will be set to true unless for some
reason the node is barred from constraint validation, such as possessing
the disabled attribute.
<div id="one"></div>
<input type="text" id="two" />
<input type="text" id="three" disabled />
<script>
[Link]('one').willValidate; //undefined
[Link]('two').willValidate; //true
[Link]('three').willValidate; //false
</script>