JavaScript DOM Exercises
JavaScript DOM Exercises
Do you want to learn more about JavaScript and how elements work. They
are objects which can hold values just like any other objects in JavaScript.
The three exercises below will demonstrate creating page elements with
JavaScript, how to add values to the element objects, and how to update
page elements. There is also an exercise on how they work with the page
element objects, and the difference between function expressions and
function declarations.
1
Web page dynamic welcome message
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div class="output">What is you name?</div>
<input type="text" name="userName">
<button>Submit</button>
<script src="app.js"></script>
</body>
Laurence Svekis https://basescripts.com/
2
</html>
3
Function Expression vs Function Declaration
This Counter
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<div class="output"></div>
<button class="btn1">Adder 1</button>
<button class="btn2">Adder 2</button>
4
<button class="btn3">Adder 3</button>
<script src="app1.js"></script>
</body>
</html>
5
btn2.onclick = adder2;
btn3.onclick = adder3;
///Function Declaration
function adder1(){
if(!this.total) {
this.total = 1;
}else{
this.total++;
}
output.textContent = `Total #1 : (${this.total})`;
}
6
Dynamic JavaScript DOM page counters
Element Objects examples
7
Dynamically create page buttons that can be used to count totals separately.
Create a button to output all the result totals. Only using JavaScript NO
HTML elements
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<script src="app2.js"></script>
</body>
</html>
Laurence Svekis https://basescripts.com/
8
const val = {
num : 2
};
const main = elemaker('div',document.body,'');
const output = elemaker('div',main,'');
for(let i=0;i<val.num;i++){
const btn = elemaker('button',main,`Button #${i+1}`);
btn.total = 0;
btn.style.backgroundColor =
'#'+Math.random().toString(16).slice(2,8);
btn.style.color = 'white';
btn.classList.add('btn');
btn.onclick = adder;
}
const output1 = elemaker('div',main,'');
const btnMain = elemaker('button',main,`All Totals`);
btnMain.onclick = ()=>{
const btns = document.querySelectorAll('.btn');
output1.innerHTML = '';
const ul = elemaker('ul',output1,'');
btns.forEach((ele,index)=>{
const li = elemaker('li',ul,`${ele.textContent} =
${ele.total}`);
li.style.backgroundColor = ele.style.backgroundColor;
li.style.color = ele.style.color;
})
}
9
function elemaker(eleT,parent,html){
const ele = document.createElement(eleT);
ele.innerHTML = html;
return parent.appendChild(ele);
}
function adder(e){
this.total++;
output.style.backgroundColor= this.style.backgroundColor;
output.innerHTML = `${this.textContent} :(${this.total})`;
}
10
DOM create Page elements adding style
Create interactive elements that can store the current color value input an
array, for later use. Also creates buttons to update the body background
color to the value of the button text. Color style and events with Dynamic
Elements DOM.
11
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Course</title>
</head>
<body>
<input type="color">
<script src="app4.js"></script>
</body>
</html>
btn2.onclick = ()=>{
holder.forEach((ele)=>{
const span = document.createElement('span');
12
main.append(span);
span.style.width = '50px';
span.style.height = '50px';
span.style.display = 'inline-block';
span.style.backgroundColor = ele;
span.onclick = ()=>{
span.remove();}
})
}
btn.onclick = ()=>{
holder.push(myInput.value);
//main.textContent = holder.toString();
const btn1 = document.createElement('button');
main.append(btn1);
btn1.textContent = myInput.value;
btn1.style.backgroundColor = myInput.value;
btn1.style.color = 'white';
btn1.onclick = ()=>{
document.body.style.backgroundColor = btn1.textContent;
}
}
myInput.onchange = (e)=>{
console.log(e.target.value);
console.log(myInput.value);
13
document.body.style.backgroundColor = myInput.value;
///console.log(this.value);
}
14
Slider from Dynamic Elements using JSON
data
Using JSON data, load the json file when the DOM content is loaded. Create
the page slides dynamically with JavaScript code. Add interaction to
navigate between slides listening for clicks on the buttons.
15
4. If it's the first item in the data then add the class of active to the first
one only
5. Add an event listener to the buttons, when clicked check if it contains
the next class, create a function named mover() to handle the result
6. Get the current element with the active class. Using traversing, get
the next sibling to the current element, if no next element exists then
select the first child of the parent slider element.
7. Get the previous element, if it's null then select the last child of the
parent slider.
8. Remove the active class for the current element, add the active class
to the new element either previous or next.
<head>
<title>JavaScript Course</title>
<style>
* {
box-sizing: border-box;
}
.main {
width: 90vw;
margin: auto;
background-color: black;
position: relative;
16
height: 300px;
overflow: hidden;
color:white;
}
.slide {
text-align:center;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: blue;
opacity: 0;
}
.slide.active {
opacity: 1;
}
.btn {
position: absolute;
bottom: 2rem;
padding: 10px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 10px;
font-size: 0.9em;
color: white;
17
cursor:pointer;
}
.btn:hover{
background-color: rgb(0, 0, 0);
}
.next {
right: 3rem;
}
.prev {
left: 3rem;
}
</style>
</head>
<body>
<div class="main">
<div>
<div class="slider">
</div>
<div class="prev btn">< Prev</div>
<div class="next btn">Next ></div>
</div>
</div>
<script src="app5.js"></script>
</body>
18
</html>
JAVASCRIPT CODE
function mover(dir){
const cur = document.querySelector('.active');
cur.classList.remove('active');
const nex = cur.nextElementSibling ||
slider.firstElementChild;
const pre = cur.previousElementSibling ||
slider.lastElementChild;
const newActive = (dir) ? nex : pre;
newActive.classList.add('active');
}
function init(){
//console.log('ready');
fetch('app5.json')
19
.then(response => response.json())
.then(data =>{
adder(data);
})
}
function adder(data){
//slider
data.forEach((item,index)=>{
const slide = document.createElement('div');
slide.classList.add('slide');
const title = document.createElement('h2');
title.textContent = item.title;
title.style.textAlign = 'center';
if(index==0) slide.classList.add('active');
const div = document.createElement('div');
div.innerHTML = item.html;
slide.append(title);
slide.append(div);
slide.style.backgroundColor = item.back;
slide.style.color = item.color;
slider.append(slide);
})
}
JSON file
[
{
20
"title": "slide 1",
"html": "<h1>Laurence</h1>",
"back": "purple",
"color": "white"
},
{
"title": "slide 2",
"html": "<h1>Svekis</h1>",
"back": "blue",
"color": "white"
}, {
"title": "slide 4",
"html": "<h1>Svekis</h1>",
"back": "blue",
"color": "white"
},
{
"title": "slide 3",
"html": "<h1>JavaScript</h1>",
"back": "yellow",
"color": "black"
}
]
21