DOM & Events
Chapter: 45
What is DOM??
The DOM
When you open any webpage in a browser, the HTML of the page is loaded and rendered visually on the screen.
To accomplish that, the browser builds the Document Object Model of that page, which is an object oriented model of its logical structure.
The DOM of an HTML document can be represented as a nested set of boxes:
JavaScript can be used to manipulate the DOM of a page dynamically to add, delete and modify elements.
The DOM
What is DOM?
DOM Tree
The DOM represents a document as a tree structure.
HTML elements become interrelated nodes in the tree.
All those nodes in the tree have some kind of relations among each other.
Nodes can have child nodes. Nodes on the same tree level are called siblings.
For example, consider the following structure:
<html> has two children (<head>, <body>);
<head> has one child (<title>) and one parent (<html>);
<title> has one parent (<head>) and no children;
<body> has two children (<h1> and <a>) and one parent (<html>);
It is important to understand the relationships between elements in an HTML document in order to be able to manipulate them with JavaScript.
DOM Tree
In the following HTML, which element is the parent of h1? <body> <p><h1>Hi</h1></p> </body>
The document Object
There is a predefined document object in JavaScript, which can be used to access all elements on the DOM.
In other words, the document object is the owner (or root) of all objects in your webpage.
So, if you want to access objects in an HTML page, you always start with accessing the document object.
For example:
document.body.innerHTML = "Some text";
JS
The innerHTML property can be used on almost all HTML elements to change its content.
Chapter: 46
Selecting Elements
Selecting Elements
All HTML elements are objects. And as we know every object has properties and methods.
The document object has methods that allow you to select the desired HTML element.
These three methods are the most commonly used for selecting HTML elements:
//finds element by id
document.getElementById(id)
//finds elements by class name
document.getElementsByClassName(name)
//finds elements by tag name
document.getElementsByTagName(name)
document.getElementById(id)
//finds elements by class name
document.getElementsByClassName(name)
//finds elements by tag name
document.getElementsByTagName(name)
JS
var elem = document.getElementById("demo");
elem.innerHTML = "Hello World!";
elem.innerHTML = "Hello World!";
JS
The example above assumes that the HTML contains an element with id="demo", for example <div id="demo"></div>.
Selecting Elements
Fill in the blanks to select the element with id="text" and change its content to "Hi".
Selecting Elements
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name.
For example, if our HTML page contained three elements with class="demo", the following code would return all those elements as an array:
var arr = document.getElementsByClassName("demo");
//accessing the second element
arr[1].innerHTML = "Hi";
//accessing the second element
arr[1].innerHTML = "Hi";
JS
The following example gets all paragraph elements of the page and changes their content:
<p>hi</p>
<p>hello</p>
<p>hi</p>
<script>
var arr = document.getElementsByTagName("p");
for (var x = 0; x < arr.length; x++) {
arr[x].innerHTML = "Hi there";
}
</script>
<p>hello</p>
<p>hi</p>
<script>
var arr = document.getElementsByTagName("p");
for (var x = 0; x < arr.length; x++) {
arr[x].innerHTML = "Hi there";
}
</script>
HTML
<p>Hi there</p>
<p>Hi there</p>
<p>Hi there</p>
<p>Hi there</p>
<p>Hi there</p>
HTML
We used the length property of the array to loop through all the selected elements in the above example.
Selecting Elements
Fill in the blanks to select all div elements and alert the content of the third div.
Working with DOM
Each element in the DOM has a set of properties and methods that provide information about their relationships in the DOM:
element.childNodes returns an array of an element's child nodes.
element.firstChild returns the first child node of an element.
element.lastChild returns the last child node of an element.
element.hasChildNodes returns true if an element has any child nodes, otherwise false.
element.nextSibling returns the next node at the same tree level.
element.previousSibling returns the previous node at the same tree level.
element.parentNode returns the parent node of an element.
We can, for example, select all child nodes of an element and change their content:
<html>
<body>
<div id ="demo">
<p>some text</p>
<p>some other text</p>
</div>
<script>
var a = document.getElementById("demo");
var arr = a.childNodes;
for(var x=0;x<arr.length;x++) {
arr[x].innerHTML = "new text";
}
</script>
</body>
</html>
<body>
<div id ="demo">
<p>some text</p>
<p>some other text</p>
</div>
<script>
var a = document.getElementById("demo");
var arr = a.childNodes;
for(var x=0;x<arr.length;x++) {
arr[x].innerHTML = "new text";
}
</script>
</body>
</html>
HTML
The code above changes the text of both paragraphs to "new text".
Working with DOM
Can a node in the DOM have multiple parent nodes?
Chapter: 47
Changing Elements
Changing Attributes
Once you have selected the element(s) you want to work with, you can change their attributes.
As we have seen in the previous lessons, we can change the text content of an element using the innerHTML property.
Similarly, we can change the attributes of elements.
For example, we can change the src attribute of an image:
<img id="myimg" src="orange.png" alt="" />
<script>
var el = document.getElementById("myimg");
el.src = "apple.png";
</script>
<script>
var el = document.getElementById("myimg");
el.src = "apple.png";
</script>
HTML
<a href="http://www.example.com">Some link</a>
<script>
var el = document.getElementsByTagName("a");
el[0].href = "http://www.sololearn.com";
</script>
<script>
var el = document.getElementsByTagName("a");
el[0].href = "http://www.sololearn.com";
</script>
HTML
Practically all attributes of an element can be changed using JavaScript.
Changing Style
The style of HTML elements can also be changed using JavaScript.
All style attributes can be accessed using the style object of the element.
For example:
<div id="demo" style="width:200px">some text</div>
<script>
var x = document.getElementById("demo");
x.style.color = "6600FF";
x.style.width = "100px"
</scrip
<script>
var x = document.getElementById("demo");
x.style.color = "6600FF";
x.style.width = "100px"
</scrip
HTML
All CSS properties can be set and modified using JavaScript. Just remember, that you cannot use dashes (-) in the property names: these are replaced with camelCase versions, where the compound words begin with a capital letter.
For example: the background-color property should be referred to as backgroundColor.
For example: the background-color property should be referred to as backgroundColor.
Chapter: 48
Adding & Removing Elements
Creating Elements
Use the following methods to create new nodes:
element.cloneNode() clones an element and returns the resulting node.
document.createElement(element) creates a new element node.
document.createTextNode(text) creates a new text node.
For example:
var node = document.createTextNode("Some new text");
JS
element.appendChild(newNode) adds a new child node to an element as the last child node.
element.insertBefore(node1, node2) inserts node1 as a child before node2.
Example:
<div id ="demo">some content</div>
<script>
//creating a new paragraph
var p = document.createElement("p");
var node = document.createTextNode("Some new text");
//adding the text to the paragraph
p.appendChild(node);
var div = document.getElementById("demo");
//adding the paragraph to the div
div.appendChild(p);
</script>
<script>
//creating a new paragraph
var p = document.createElement("p");
var node = document.createTextNode("Some new text");
//adding the text to the paragraph
p.appendChild(node);
var div = document.getElementById("demo");
//adding the paragraph to the div
div.appendChild(p);
</script>
HTML
This creates a new paragraph and adds it to the existing div element on the page.
Creating Elements
Drag and drop from the options below to add a new <li> element to the unordered list with id="list".
Removing Elements
To remove an HTML element, you must select the parent of the element and use the removeChild(node) method.
For example:
<div id="demo">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.removeChild(child);
</script>
HTML
An alternative way of achieving the same result would be the use of the parentNode property to get the parent of the element we want to remove:
var child = document.getElementById("p1");
child.parentNode.removeChild(child);
var child = document.getElementById("p1");
child.parentNode.removeChild(child);
Removing Elements
Drag and drop from the options below to remove the node element from the page (par is node's parent).
Replacing Elements
To replace an HTML element, the element.replaceChild(newNode, oldNode) method is used.
For example:
<div id="demo">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.replaceChild(p, child);
</script>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var p = document.createElement("p");
var node = document.createTextNode("This is new");
p.appendChild(node);
var parent = document.getElementById("demo");
var child = document.getElementById("p1");
parent.replaceChild(p, child);
</script>
HTML
The code above creates a new paragraph element that replaces the existing p1 paragraph.
Replacing Elements
Which method is used to replace nodes?
Chapter: 49
Creating Animations
Animations
Now that we know how to select and change DOM elements, we can create a simple animation.
Let's create a simple HTML page with a box element that will be animated using JS.
<style>
#container {
width: 200px;
height: 200px;
background: green;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: red;
position: absolute;
}
</style>
<div id="container">
<div id="box"> </div>
</div>
#container {
width: 200px;
height: 200px;
background: green;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: red;
position: absolute;
}
</style>
<div id="container">
<div id="box"> </div>
</div>
HTML
You need to be familiar with CSS to better understand the code provided.
Animations
To create an animation relative to a container, the position attribute for the container should be set to:
Animations
To create an animation, we need to change the properties of an element at small intervals of time. We can achieve this by using the setInterval() method, which allows us to create a timer and call a function to change properties repeatedly at defined intervals (in milliseconds).
For example:
var t = setInterval(move, 500);
JS
Now we need to define the move() function, that changes the position of the box.
// starting position
var pos = 0;
//our box element
var box = document.getElementById("box");
function move() {
pos += 1;
box.style.left = pos+"px"; //px = pixels
}
var pos = 0;
//our box element
var box = document.getElementById("box");
function move() {
pos += 1;
box.style.left = pos+"px"; //px = pixels
}
JS
The move() function increments the left property of the box element by one each time it is called.
Animations
What is the interval for this timer? var t = setInterval(func, 10000);
Animations
The following code defines a timer that calls the move() function every 10 milliseconds:
var t = setInterval(move, 10);
JS
function move() {
if(pos >= 150) {
clearInterval(t);
}
else {
pos += 1;
box.style.left = pos+"px";
}
}
if(pos >= 150) {
clearInterval(t);
}
else {
pos += 1;
box.style.left = pos+"px";
}
}
JS
The final code:
var pos = 0;
//our box element
var box = document.getElementById("box");
var t = setInterval(move, 10);
function move() {
if(pos >= 150) {
clearInterval(t);
}
else {
pos += 1;
box.style.left = pos+"px";
}
}
//our box element
var box = document.getElementById("box");
var t = setInterval(move, 10);
function move() {
if(pos >= 150) {
clearInterval(t);
}
else {
pos += 1;
box.style.left = pos+"px";
}
}
JS
Congratulations, you have just created your first JavaScript animation!
Animations
Which function is used to stop a setInterval timer?
Chapter: 50
Handling Events
Events
You can write JavaScript code that executes when an event occurs, such as when a user clicks an HTML element, moves the mouse, or submits a form.
When an event occurs on a target element, a handler function is executed.
Common HTML events include:
Corresponding events can be added to HTML elements as attributes.
For example: <p onclick="someFunc()">some text</p>
For example: <p onclick="someFunc()">some text</p>
Events
The type of function that executes when an event occurs is called:
Handling Events
Let's display an alert popup when the user clicks a specified button:
<button onclick="show()">Click Me</button>
<script>
function show() {
alert("Hi there");
}
</script>
<script>
function show() {
alert("Hi there");
}
</script>
HTML
For example:
var x = document.getElementById("demo");
x.onclick = function () {
document.body.innerHTML = Date();
}
x.onclick = function () {
document.body.innerHTML = Date();
}
JS
You can attach events to almost all HTML elements.
Handling Events
Fill in the blanks to call func() when the button is clicked.
Events
The onload and onunload events are triggered when the user enters or leaves the page. These can be useful when performing actions after the page is loaded.
<body onload="doSomething()">
HTML
window.onload = function() {
//some code
}
//some code
}
JS
For example:
<input type="text" id="name" onchange="change()">
<script>
function change() {
var x = document.getElementById("name");
x.value= x.value.toUpperCase();
}
</script>
<script>
function change() {
var x = document.getElementById("name");
x.value= x.value.toUpperCase();
}
</script>
HTML
It’s important to understand events, because they are an essential part of dynamic web pages.
Events
Drag and drop from the options below to call the clear() function after body is loaded.
Event Listeners
The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element.
You can also add many event handlers of the same type to one element, i.e., two "click" events.
element.addEventListener(event, function, useCapture);
JS
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, and will be described in the next lesson.
Note that you don't use the "on" prefix for this event; use "click" instead of "onclick".
element.addEventListener("click", myFunction);
element.addEventListener("mouseover", myFunction);
function myFunction() {
alert("Hello World!");
}
element.addEventListener("mouseover", myFunction);
function myFunction() {
alert("Hello World!");
}
JS
We can remove one of the listeners:
element.removeEventListener("mouseover", myFunction);
JS
<button id="demo">Start</button>
<script>
var btn = document.getElementById("demo");
btn.addEventListener("click", myFunction);
function myFunction() {
alert(Math.random());
btn.removeEventListener("click", myFunction);
}
</script>
<script>
var btn = document.getElementById("demo");
btn.addEventListener("click", myFunction);
function myFunction() {
alert(Math.random());
btn.removeEventListener("click", myFunction);
}
</script>
HTML
Internet Explorer version 8 and lower do not support the addEventListener() and removeEventListener() methods. However, you can use the document.attachEvent() method to attach event handlers in Internet Explorer.
Event Listeners
Can multiple event handlers be added to a single element?
Chapter: 51
Event Propagation
Event Propagation
There are two ways of event propagation in the HTML DOM: bubbling and capturing.
Event propagation allows for the definition of the element order when an event occurs. If you have a <p> element inside a <div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?
In bubbling, the innermost element's event is handled first and then the outer element's event is handled. The <p> element's click event is handled first, followed by the <div> element's click event.
In capturing, the outermost element's event is handled first and then the inner. The <div> element's click event is handled first, followed by the <p> element's click event.
Capturing goes down the DOM.
Bubbling goes up the DOM.
Bubbling goes up the DOM.
Event Propagation
A paragraph is inside a div element. You want the paragraph’s click event to be handled first. You should use:
Capturing vs. Bubbling
The addEventListener() method allows you to specify the propagation type with the "useCapture" parameter.
addEventListener(event, function, useCapture)
JS
The default value is false, which means the bubbling propagation is used; when the value is set to true, the event uses the capturing propagation.
//Capturing propagation
elem1.addEventListener("click", myFunction, true);
//Bubbling propagation
elem2.addEventListener("click", myFunction, false);
elem1.addEventListener("click", myFunction, true);
//Bubbling propagation
elem2.addEventListener("click", myFunction, false);
JS
This is particularly useful when you have the same event handled for multiple elements in the DOM hierarchy.
Capturing vs. Bubbling
Drag and drop from the options below to handle the click event and use capturing propagation.
Chapter: 52
Creating an Image Slider
Image Slider
Now we can create a sample image slider project. The images will be changed using "Next" and "Prev" buttons.
Now, let’s create our HTML, which includes an image and the two navigation buttons:
<div>
<button> Prev </button>
<img id="slider" src="http://www.sololearn.com/uploads/slider/1.jpg"
width="200px" height="100px"/>
<button> Next </button>
</div>
<button> Prev </button>
<img id="slider" src="http://www.sololearn.com/uploads/slider/1.jpg"
width="200px" height="100px"/>
<button> Next </button>
</div>
HTML
var images = [
"http://www.sololearn.com/uploads/slider/1.jpg",
"http://www.sololearn.com/uploads/slider/2.jpg",
"http://www.sololearn.com/uploads/slider/3.jpg"
];
"http://www.sololearn.com/uploads/slider/1.jpg",
"http://www.sololearn.com/uploads/slider/2.jpg",
"http://www.sololearn.com/uploads/slider/3.jpg"
];
JS
We are going to use three sample images that we have uploaded to our server. You can use any number of images.
Image Slider
Fill in the blanks to define an array.
Image Slider
Now we need to handle the Next and Prev button clicks and call the corresponding functions to change the image.
HTML:
<div>
<button onclick="prev()"> Prev </button>
<img id="slider" src="http://www.sololearn.com/uploads/slider/1.jpg"
width="200px" height="100px"/>
<button onclick="next()"> Next </button>
</div>
<button onclick="prev()"> Prev </button>
<img id="slider" src="http://www.sololearn.com/uploads/slider/1.jpg"
width="200px" height="100px"/>
<button onclick="next()"> Next </button>
</div>
HTML
var images = [
"http://www.sololearn.com/uploads/slider/1.jpg",
"http://www.sololearn.com/uploads/slider/2.jpg",
"http://www.sololearn.com/uploads/slider/3.jpg"
];
var num = 0;
function next() {
var slider = document.getElementById("slider");
num++;
if(num >= images.length) {
num = 0;
}
slider.src = images[num];
}
function prev() {
var slider = document.getElementById("slider");
num--;
if(num < 0) {
num = images.length-1;
}
slider.src = images[num];
}
"http://www.sololearn.com/uploads/slider/1.jpg",
"http://www.sololearn.com/uploads/slider/2.jpg",
"http://www.sololearn.com/uploads/slider/3.jpg"
];
var num = 0;
function next() {
var slider = document.getElementById("slider");
num++;
if(num >= images.length) {
num = 0;
}
slider.src = images[num];
}
function prev() {
var slider = document.getElementById("slider");
num--;
if(num < 0) {
num = images.length-1;
}
slider.src = images[num];
}
JS
We have created a functioning image slider!
Image Slider
What will be the content of the paragraph after the user clicks on it twice? <p id='txt' onclick='test();'>20</p> <script> function test() { var x=document.getElementById('txt'); var n = x.innerHTML; x.innerHTML = n/2; } </script>
Chapter: 53
Form Validation
Form Validation
HTML5 adds some attributes that allow form validation. For example, the required attribute can be added to an input field to make it mandatory to fill in.
More complex form validation can be done using JavaScript.
The form element has an onsubmit event that can be handled to perform validation.
For example, let's create a form with two inputs and one button. The text in both fields should be the same and not blank to pass the validation.
<form onsubmit="return validate()" method="post">
Number: <input type="text" name="num1" id="num1" />
<br />
Repeat: <input type="text" name="num2" id="num2" />
<br />
<input type="submit" value="Submit" />
</form>
Number: <input type="text" name="num1" id="num1" />
<br />
Repeat: <input type="text" name="num2" id="num2" />
<br />
<input type="submit" value="Submit" />
</form>
HTML
function validate() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
if(n1.value != "" && n2.value != "") {
if(n1.value == n2.value) {
return true;
}
}
alert("The values should be equal and not blank");
return false;
}
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
if(n1.value != "" && n2.value != "") {
if(n1.value == n2.value) {
return true;
}
}
alert("The values should be equal and not blank");
return false;
}
JS
The form will not get submitted if its onsubmit event returns false.







Comments
Post a Comment