Start with this array:
var a = [45, 97, 12, 30, 51, 3, 61];
Write a for loops that computes these values:
- the count of the numbers in the array,
- the count of the numbers between 40 and 60 inclusive,
- the average of all the numbers.
Put the answers in an ordered list that is dynamically generated.
Start with a body that contains only an h1 element. Answer:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Exercise 1</title>
<style>
ol { list-style-type: lower-alpha; }
</style>
<script>
function performComputations( ) {
var a = [45, 97, 12, 30, 51, 3, 61];
var bodyObj = document.querySelector("body");
var olObj = document.createElement("ol");
bodyObj.appendChild(olObj);
// Question 1a
var count1 = 0;
for(var n of a) {
count1++;
}
// Can also obtain count1 with this single statement:
// var count1 = a.length;
var liObj = document.createElement("li");
liObj.innerHTML = count1;
olObj.appendChild(liObj);
// Question 1b
var count2 = 0;
for(var n of a) {
if (40 <= n && n <= 60) {
count2++;
}
}
var liObj = document.createElement("li");
liObj.innerHTML = count2;
olObj.appendChild(liObj);
// Question 1c
var count = 0;
var sum = 0.0;
for(var n of a) {
count++;
sum += n;
}
var average = sum / count;
var liObj = document.createElement("li");
liObj.innerHTML = average.toFixed(2);
olObj.appendChild(liObj);
}
window.addEventListener("load", performComputations);
</script>
</head>
<body>
<h1>Exercise 1</h1>
</body>
</html>
Use these images to test the following jQuery script:
elephant.jpg
lion.jpg
monkey.jpg
rhinoceros.jpg
$( function( ) {
$("img").mouseenter( function( ) {
$(this).css("width", "200px");
});
$("img").mouseleave( function( ) {
$(this).css("width", "150px");
});
};
Translate this script to vanilla JavaScript. Here is the entire HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Exercise 3</title>
<style>
img { width: 150px; }
</style>
<script src="jquery-3.7.1min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function( ) {
var imgArray = document.querySelectorAll("img");
for(var anImg of imgArray) {
anImg.addEventListener("mouseenter", function(e) {
e.target.style.width = "200px";
});
}
for(var anImg of imgArray) {
anImg.addEventListener("mouseleave", function(e) {
e.target.style.width = "150px";
});
}
});
</script>
</head>
<body>
<h1>Exercise 3</h1>
<img src="images/elephant.jpg" alt="Elephant">
<img src="images/lion.jpg" alt="Lion">
<img src="images/monkey.jpg" alt="Monkey">
<img src="images/rhinoceros.jpg" alt="Rhinoceros">
</body>
</html>