Vous êtes sur la page 1sur 28

JavaScript

Get the Course


https://www.udemy.com/course/learn-javascript-dom-course

JavaScript DOM Dynamic Web interactive content


INSTRUCTOR:

LAURENCE SVEKIS
- Over 300 courses in technology and
web applications.
- 20 years of JavaScript web
programming experience
- 500,000+ students across multiple
platforms
- Digital instructor since 2002

READY TO HELP YOU LEARN and


ANSWER ANY questions you may
have.

Course instructor : Laurence Svekis


JavaScript on Web Page
1. Create index.html page <!doctype html>
<html>
2. Add JavaScript within html page <head>
<title>JavaScript Page</title>
3. Link to JavaScript file within </head>

HTML page <body>


<p id="idOne"></p>
4. Try the code <script>
document.write('Hello World');
console.log('hello');
const x = 'Hello';
document.getElementById("idOne").innerHTML = x;
</script>
<script src="script.js"></script>
</body>
</html>

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Console Log
The Console method log() outputs a message <!doctype html>
<html>
to the web console. The message may be a <head>

single string (with optional substitution <title>JavaScript Page</title>


values), or it may be any one or more </head>
<body>
JavaScript objects. <p id="idOne">Hello World</p>
<script>
https://developer.mozilla.org/en-US/docs/Web var myvar = document.getElementById('idOne').textContent;
console.log(myvar, "Logged!");
/API/Console/log console.info(myvar, "Logged!");
console.warn(myvar, "Logged!");
console.debug(myvar, "Logged!");
1. Get textContent of Element console.error(myvar, "Logged!");
console.log('%c I see smurfs!', 'color: green; font-weight: bold;');
2. Console log messages console.log('%c I see the sky!', 'background: blue; font-weight: bold;');
</script>
3. Console log values </body>

</html>

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Document Object
The Document interface represents any web <!doctype html>
<html>
page loaded in the browser and serves as an <head>
<title>JavaScript Page</title>
entry point into the web page's content, </head>
which is the DOM tree. The DOM tree includes <body>
<script>
elements such as <body> and <table>, among document.body.innerHTML = "New webPage content";
console.log(document.body);
many others. It provides functionality console.dir(document.body);
console.dir(document);
globally to the document </script>
https://developer.mozilla.org/en-US/docs/Web </body>
</html>
/API/Document

1. Select the document body - update


page contents
2. View the document and body in the
console using dir and log.

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript WEBSITE DOM
<!DOCTYPE html><html><head> <title>JavaScript DOM</title></head><body> <nav role="navigation" class="navbar
Selecting the elements on the page is the navbar-default"> <div class="navbar-header"> <button type="button" data-target="#navbarCollapse"
data-toggle="collapse" class="navbar-toggle"> <span class="sr-only">Toggle navigation</span> <span
first step before manipulating the element. class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="#"
class="navbar-brand">Home Page</a> </div> <div id="navbarCollapse" class="collapse navbar-collapse"> <ul
There are a number of ways to make element class="nav navbar-nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a
href="#">Contact</a></li> </ul> </div> </nav> <div class="container"> <h1 id="header">Welcome to My Website</h1>
selections. <div id="topSection" class="row"> <p><span class="second">A</span> This is my website which <span
class="first">can</span> change!</p> <p><span class="second">B</span> Are you going to see what <a
href="http://www.google.com?s=JSAJAX">Everything</a> happens when the word <span class="first">can</span>
changes?</p> <p><span class="second">C</span> Elements can <a href="http://www.google.com?s=JS">Just
JS</a> change and you <span class="first">can</span> select them by Class, ID and other methods.</p> <div
1. Create a website with a number of class="first"><span class="second">D</span> This is a Div with the class that is the same as the spans</div> </div>
<div id="outPut" class="row"> <p id="outputContent" class="outputClass"> This is where the content will change!!!
<span class="first">span</span> <span class="first">This is just a new div</span></p> </div> <div class="row"> <p>
elements you can use the website Buttons</p> <button id="btnA">Button A</button> <button id="btnB">Button B</button> <button id="btnC">Button
C</button> </div> <div class="row"> <p> Lists</p> <ul> <li id="listA" class="listClass">List A</li> <li id="listB"
code posted on the right → class="listClass">List B</li> <li id="listC" class="listClass">List C</li> <li id="listD" class="listClass">List D</li> <li
id="listE" class="listClass">List E</li> </ul> </div> <div class="row"> <p> Form</p> <form> Name : <input
name="firstName" type="text" id="firstName" value="firstName value"> <br> Email : <input name="email" type="email"
2. Update the script files select id="email"> <br> <input name="submitButton" type="submit" id="submitButton"> </form> </div> <div class="row"> <p>
Images Links</p> <p>We had to place some links to <a href="http://www.discoveryvip.com"> websites </a> </p> <p>

the element with id header and Update this code to improve on the site experience. This is just a second <span class="second">span</span> <span
class="second">This is another new div</span> In this section we added some images</p> <p> <img id="myImage"
src="https://via.placeholder.com/150" alt="temp image"> </p> </div> <div id="footer" class="row"> <div> Copyright ©
update the textContent discoveryvip.com </div> </div> </div> <script src="script.js"></script></body></html>

const header = document.getElementById('header');


console.log(header);
header.textContent = 'New header Content';

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Selecting by TAG
The Element.getElementsByTagName() method const el1 = document.querySelector('h1');
el1.textContent = 'First H1 on Page';
returns a live HTMLCollection of elements console.log(el1);
const el2 = document.getElementsByTagName('h1'); // return HTMLcollection
with the given tag name. All descendants of el2.textContent = 'First H1 by Tag';
console.log(el2);
the specified element are searched, but not el2[0].textContent = 'First H1 by Tag';
the element itself. The returned list is console.log(el2[0]);

live, which means it updates itself with the


DOM tree automatically. Therefore, there is
no need to call
Element.getElementsByTagName() with the same
element and arguments repeatedly if the DOM
changes in between calls.

1. Select the element in different


ways
2. Update the textContent

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript QUERYSELECTOR
The Document method querySelector() returns const el1 = document.querySelector('h1');
el1.textContent = 'First H1 on Page';
the first Element within the document that const el2 = document.querySelector('.second');
el2.textContent = 'First element with class of second';
matches the specified selector, or group of const el3 = document.querySelector('#btnA');
el3.textContent = 'Element with matching id';
selectors. If no matches are found, null is
returned.
https://developer.mozilla.org/en-US/docs/Web
/API/Document/querySelector

1. Select by tag
2. Select by class .
3. Select by id #

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript QUERYSELECTORALL
The Document method querySelectorAll() const els1 = document.querySelectorAll('p');
console.log(els1);
returns a static (not live) NodeList const els2 = document.querySelectorAll('p .second');
console.log(els2);
representing a list of the document's const els3 = document.querySelectorAll("div .first"); /// css selector
elements that match the specified group of console.log(els3);
for (var i = 0; i < els3.length; i++) {
selectors. console.log(els3[i]);
els3[i].innerHTML = els3[i].textContent + ' <b>' + i + '</b>';
https://developer.mozilla.org/en-US/docs/Web }
/API/Document/querySelectorAll

1. Select by tag
2. Select by class .
3. Loop elements from nodelist

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript QUERYSELECTORALL
You can use CSS type selectors to pinpoint const myValues = document.querySelectorAll("a[href*=\"JS\"]");
for (var i = 0; i < myValues.length; i++) {
the elements, including selecting by console.log(myValues[i].innerHTML);
myValues[i].textContent = "THIS IS CHANGED " + i;
attributes and more. myValues[i].href = "http://www.google.com?s=CHANGED";
Also Select only elements from the parent. }
const container = document.querySelector("ul.nav");
console.log(container);
const matches = container.querySelectorAll("li.active ");
1. Select all the have href linking console.log(matches);
console.log(matches[0]);
to JS in the URL.
2. Use the parent selection element
as the object to select from.

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Update Attributes
Select all the images and update height and const myImgs = document.getElementsByTagName("img");
for (var i = 0; i < myImgs.length; i++) {
title. myImgs[i].height = 20;
myImgs[i].title = myImgs[i].alt;
}
1. Selection of page images
2. Update attributes

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript childNodes Children
List out children and childnodes from const uList = document.getElementsByTagName('ul')[1];
console.log(uList);
selected element. View node types. console.log(uList.childNodes);
console.log(uList.children);
https://developer.mozilla.org/en-US/d for (var i = 0; i < uList.children.length; i++) {
console.log(uList.children[i]);
ocs/Web/API/Node/nodeType console.log(uList.children[i].nodeType);
}
for (var i = 0; i < uList.childNodes.length; i++) {
console.log(uList.childNodes[i]);
1. Select children and childnodes of console.log(uList.childNodes[i].nodeType);
}
same element. const myDiv = document.querySelectorAll('li');
console.log(myDiv);
2. Note nodeType of each for (var i = 0; i < myDiv.length; i++) {
console.log(myDiv[i].firstChild.data);
3. Get data of selected element }

var dList = document.getElementsByTagName('div')[3];


console.log(dList);
console.log(dList.childNodes[1]);
console.log(dList.childNodes[1].childNodes[1]);

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript ELEMENT STYLE UPDATE
The HTMLElement.style property is used to const headerElement = document.getElementById("header");
headerElement.innerHTML = 'This is my new Header';
get as well as set the inline style of an headerElement.style.color = 'blue';
headerElement.style.backgroundColor = "yellow";
element. headerElement.style.fontFamily = 'Cambria, "Hoefler Text", "Liberation Serif", Times,
https://developer.mozilla.org/en-US/docs/Web "Times New Roman", serif';
headerElement.style.border = '5px solid black';
/API/HTMLElement/style

1. Select an element
2. Update its style

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Multiple ELEMENT STYLE UPDATE
The HTMLElement.style property is used to const rowElement = document.getElementsByClassName("row");
for (var i = 0 ; i < rowElement.length; i++) {
get as well as set the inline style of an rowElement[i].style.textAlign = "center";
rowElement[i].style.color = 'blue';
element. rowElement[i].style.backgroundColor = "red";
https://developer.mozilla.org/en-US/docs/Web rowElement[i].style.fontFamily = 'Cambria, "Hoefler Text", "Liberation Serif", Times,
"Times New Roman", serif';
/API/HTMLElement/style rowElement[i].style.border = '1px solid black';
}

1. Select an elements
2. Update their style

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Add Class to Element
Create a class with some styling. <style>
.newStyle {
The className property of the Element color: #F8373B;
background-color: #FAFFCE;
interface gets and sets the value of text-align: center;
font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New
the class attribute of the specified Roman", serif;
}
element. The Element.classList is a .red{
.blue{
color:red;
color:blue;
}
}
read-only property that returns a </style>

live DOMTokenList collection of the


const rowElement = document.querySelectorAll(".row");
class attributes of the element. for (var i = 0; i < rowElement.length; i++) {
rowElement[i].className += " newStyle";
https://developer.mozilla.org/en-US/d }
rowElement.forEach(function (el, index) {
ocs/Web/API/Element/className console.log(el);
console.log(index);
https://developer.mozilla.org/en-US/d el.classList.add('red');
el.classList.toggle('blue');
ocs/Web/API/Element/classList el.classList.remove('row');
})

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript SetAttribute
Sets the value of an attribute on the const btn= document.querySelector('button');
btn.setAttribute('id','myButton');
specified element. If the attribute console.log(btn.id);

already exists, the value is updated;


otherwise a new attribute is added
with the specified name and value.

To get the current value of an


attribute, use getAttribute(); to
remove an attribute, call
removeAttribute().

https://developer.mozilla.org/en-US/d
ocs/Web/API/Element/setAttribute

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript createElement Add New Element
In an HTML document, the const ul = document.querySelector('.row ul');
const li = document.createElement("li");
document.createElement() method li.appendChild(document.createTextNode("List F"));
li.setAttribute("id","listF");
creates the HTML element specified by li.classList.add("red");
console.log(li);
tagName, or an HTMLUnknownElement if ul.appendChild(li);

tagName isn't recognized.

https://developer.mozilla.org/en-US/d
ocs/Web/API/Document/createElement

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Append and ++
The Node.appendChild() method adds a const vals = [200, 400, 500];
const main = document.querySelector('.container');
node to the end of the list of vals.forEach(function (v) {
let html = '<img src="https://via.placeholder.com/' + v + 'x100/0000ff"><br>';
children of a specified parent node. main.innerHTML += html;
main.prepend(html);
})
vals.forEach(function (v) {
https://developer.mozilla.org/en-US/d let img = document.createElement('img');
img.src = 'https://via.placeholder.com/' + v + 'x100/00ff00';
ocs/Web/API/Node/appendChild main.appendChild(img);
main.prepend(img); // same object can only be in one place!!!
})

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript addEventListener
The EventTarget method const myButton = document.getElementById("btnA");
const myOutput = document.querySelector('.container');
addEventListener() sets up a function const btnClick = function () {
myOutput.textContent = "You clicked the first button!";
that will be called whenever the };
myButton.addEventListener("click", btnClick);
specified event is delivered to the
target.

https://developer.mozilla.org/en-US/d
ocs/Web/API/EventTarget/addEventListe
ner

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript addEventListenerS
useCapture = true const myBtns = document.querySelectorAll('button');
const myOutput = document.querySelector('.container');
let cnt = 0;
for (var i = 0; i < myBtns.length; i++) {
The handler is set on the capturing myBtns[i].addEventListener('click', btnClick, false);
}
phase. Events will get to it before
function btnClick(e) {
getting to its children. cnt++;
console.log(e);
console.log(this);
console.log(e.target);
useCapture = false.- default e.target.style.backgroundColor = 'red';
this.textContent = "You clicked this button <" + cnt + ">";
};

The handler is set on the bubbling


phase. Events will get to it after
getting to its children.

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript MOUSEMOVE
Select the element to apply event const myOutput = document.querySelector('.container');
const header = document.querySelector('#header');
listener on. Use mouse move and get const mouseMover = function (e) {
console.log(e);
the position. console.log(e.x);
header.textContent = "x is at " + e.x + " y is at " + e.y;
};
myOutput.addEventListener("mousemove", mouseMover);

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript MOUSEMOVE on Image Do something
Make some images. Detect mouse const num = 10;
const output = document.createElement('div');
movements on images. const myOutput = document.querySelector('.container');
output.setAttribute('class', 'red');
1. Create number of images output.style.fontSize = '3em';
output.textContent = "welcome";
dynamically document.body.prepend(output);
for (let x = 0; x < num; x++) {
2. Select all page images let img = document.createElement('img');
let clr = Math.random().toString(16).substr(-6);
3. Add event listeners to all images img.src = 'https://via.placeholder.com/100x100/' + clr;
myOutput.prepend(img);
for mouse over and mouse out }
const myImages = document.querySelectorAll('img');
4. Update output element background myImages.forEach(function (el) {
el.addEventListener("mousemove", mouseMover);
with image background color. el.addEventListener("mouseleave", mouseMoverOut);
})
function mouseMover(e) {
output.textContent = "You are over the image!!! " + this.src.substr(-6);;
output.style.backgroundColor = '#' + this.src.substr(-6);
};
function mouseMoverOut(e) {
output.textContent = "You moved off the image " + this.src.substr(-6);;
output.style.backgroundColor = "white";
};

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript FORM VALUES
The Event interface's const myOutput = document.getElementById("header");
const myButton = document.getElementById("submitButton");
preventDefault() method tells the const btnClick = function (e) {
e.preventDefault();
user agent that if the event does not let messageOut;
let name = document.getElementById("firstName").value;
get explicitly handled, its default let email = document.getElementById("email").value;
if (name) {
action should not be taken as it messageOut = "Hello " + name;
}
normally would be. else {
messageOut = "Mysterious person I wonder why you don't add your name.";
https://developer.mozilla.org/en-US/d }
myOutput.textContent = messageOut;
ocs/Web/API/Event/preventDefault };
myButton.addEventListener("click", btnClick);

1. Select the value from a form


2. Prevent default on form submit

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript a link stopper
Use prevent default to stop all links const links = document.querySelectorAll('a');
links.forEach(function(el){
from being clickable on the page. el.addEventListener('click',function(e){
e.preventDefault()
console.log(e);
console.log('clicked');
1. Select all hyperlinks console.log(this.getAttribute('href'));
})
2. Add prevent default })

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript WINDOW OBJECT
The Window interface represents a console.log(window);
///Window Object Properties
window containing a DOM document; the console.log(window.screen.height);
console.log(window.scrollX);
document property points to the DOM console.log(window.history.length);
console.log(window.location);
document loaded in that window. console.log(window.navigator.userAgent);

https://developer.mozilla.org/en-US/d ///Window Object Methods


window.open("", "", "width=100, height=100");
ocs/Web/API/Window window.resizeTo(250, 250);
setInterval(function(){ console.log("This message will show every 5 seconds"); }, 5000);

1. Open new window

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript Annoying Blinker
Select all the buttons on the page let blinky;
const myButton = document.getElementById("submitButton");
that will stop the text blinking const myOutput = document.querySelector('.container');
const btns = document.querySelectorAll('button');
colors. btns.forEach(function (el) {
el.addEventListener("click", stopChangeText);
})
blinky = setInterval(changeText, 100);
1. Create interval that updates main
function changeText() {
element background and color myOutput.style.color = myOutput.style.color == "red" ? "black" : "red";
myOutput.style.backgroundColor = '#' + Math.random().toString(16).substr(-6);
2. Add eventlisteners to all buttons }

on the page function stopChangeText(e) {


e.preventDefault();
3. Click button stop the blinking clearInterval(blinky);
}

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


JavaScript ANIMATIONS :)
The window.requestAnimationFrame() let stopper = false;let dir = 1;
const mover = document.createElement('div');
method tells the browser that you const myOutput = document.querySelector('.container');
mover.style.position = 'absolute';mover.style.left = '10px';mover.style.top =
wish to perform an animation and '100px';mover.style.backgroundColor = 'red';mover.style.padding =
'20px';mover.textContent = 'catch me';mover.style.color = 'white';
requests that the browser call a mover.addEventListener('click', animateMe);
myOutput.appendChild(mover);
specified function to update an let animator = window.requestAnimationFrame(render);
function animateMe(e) {
animation before the next repaint. if (stopper) {
animator = window.requestAnimationFrame(render);
stopper = false;
console.log(dir);
1. Create an element dir *= -1;
}
2. Animate it else {
window.cancelAnimationFrame(animator);
3. Add event listener to toggle stopper = true;
}
direction }
function render() {
let pos = mover.offsetLeft;
console.log(pos);
mover.style.left = (pos + dir) + "px";
animator = window.requestAnimationFrame(render);
}

Get the Course https://www.udemy.com/course/learn-javascript-dom-course


Congratulations on completing the course!
Thank you for your support
Check out more about JavaScript at MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript

Find out more about my courses at http://discoveryvip.com/

Course instructor : Laurence Svekis -


providing online training to over
500,000 students across hundreds of
courses and many platforms.

Get the Course


https://www.udemy.com/course/learn-javascript-dom-course

Vous aimerez peut-être aussi