Chapter 7 - JavaScript Functions, Events and Loops
Chapter 7 - JavaScript Functions, Events and Loops
Development &
Application
Example:
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
JavaScript Function Syntax
A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
function myFunction(){
//do
}
myFunction();
Function Return
When JavaScript reaches a return statement, the function will stop executing.
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
Function Return
When JavaScript reaches a return statement, the function will stop executing.
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
JavaScript Objects
In real life, objects are things like: houses, cars, people, animals, or any
other subjects.
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named car:
const person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue“
};
• objectName.propertyName;
• objectName["propertyName"];
Example:
person.lastName;
//is the same as
person["lastName"];
JavaScript Object Methods
Methods are actions that can be performed on objects.
Methods are function definitions stored as property values.
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In JavaScript, Objects are King.
If you Understand Objects, you Understand JavaScript.
• Objects are containers for Properties and Methods.
• Properties are named Values.
• Methods are Functions stored as Properties.
• Properties can be primitive values, functions, or even other objects.
const person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
}
const x = person;
x.age = 10;
document.write(person.firstName + " is " + person.age + " years old.");
Loops
Loops execute a block of code a specified number of times or while a specified
condition is true.
Often when you write code, you want the same block of code to run over and over
again in a row. Instead of adding several almost equal lines in a script, you
can use loops to perform a task like this.
let i = 0;
while (i<=5){
document.write("The number is " + i);
document.write("<br />");
i++;
}
The do… while Loop
The do...while loop is a variant of the while loop. This loop will execute the
block of code once, and then it will repeat the loop as long as the specified
condition is true.
i = 0;
do{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i <= 5);
The break and continue
Statement
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.
Many different methods can be used to let JavaScript work with events:
• HTML event attributes can execute JavaScript code directly
• HTML event attributes can call JavaScript functions
• You can assign your own event handler functions to HTML elements
• You can prevent events from being sent or being handled
• And more ...
The HTML DOM (Document
Object
When a web pageModel)
is loaded, the browser creates a Document Object Model of the
page.
The HTML DOM model is constructed as a tree of Objects:
What is HTML DOM?
The HTML DOM is a standard object model and programming interface for HTML. It
defines:
In other words: The HTML DOM is a standard for how to get, change, add, or
delete HTML elements.
JavaScript - HTML DOM Methods
The DOM Programming Interface
• The HTML DOM can be accessed with JavaScript (and with other programming
languages).
• 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).
JavaScript - HTML DOM Methods
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
const x = document.getElementById("main");
const y = x.getElementsByTagName("p");
Finding HTML Elements
Finding HTML Elements by Class Name
const x = document.getElementByClassName("intro");
const x = document.querySelectorAll("p.intro");
JavaScript - HTML DOM
Document
container.appendChild(newHeading);
container.appendChild(otherHeading);
container.removeChild(otherHeading);
container.replaceChild(otherHeading, newHeading);
JavaScript - HTML DOM
Document
<html>
<body>
<button id="demo">Click Me</button>
<div id="div"></div>
<script>
document.getElementById("demo").onclick = function(){
document.getElementById("div").innerHTML = "Hello, Javascript";
}
</script>
</body>
</html>
JavaScript - HTML DOM
Document
Finding HTML Objects
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Validation</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb"> <!-- make it a type="number" to only allow number inputs -->
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
let x = document.getElementById("numb").value;
let text;
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and
useful.
Server side validation is performed by a web server, after input has been sent to
the server.
Server side validation is performed by a web server, after input has been sent to
the server.
You can easily remove an event listener by using the removeEventListener() method.
Syntax:
element.addEventListener(event, function, useCapture);
element.addEventListener(event, function); //must use a named function to remove an event
Example:
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello World!");
});
Add Many Event Handlers to the Same
Element
The addEventListener() method allows you to add many events to the same element,
without overwriting existing events:
element.addEventListener("click", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Activity:
Modify the code below to accomplish the
following objectives: