Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Chapter 7 - JavaScript Functions, Events and Loops

The document provides an overview of JavaScript functions, objects, loops, events, and form validation. It explains how to define and invoke functions, create and manipulate objects, use loops for repetitive tasks, handle events in HTML, and perform data validation. Additionally, it covers the HTML Document Object Model (DOM) and methods for interacting with HTML elements using JavaScript.

Uploaded by

marjune.gabon07
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 7 - JavaScript Functions, Events and Loops

The document provides an overview of JavaScript functions, objects, loops, events, and form validation. It explains how to define and invoke functions, create and manipulate objects, use loops for repetitive tasks, handle events in HTML, and perform data validation. Additionally, it covers the HTML Document Object Model (DOM) and methods for interacting with HTML elements using JavaScript.

Uploaded by

marjune.gabon07
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

WD 101: Web

Development &
Application

JavaScript Functions, Events and Loops


JavaScript Functions
A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).

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, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:

• When an event occurs (when a user clicks a button)


• When it is invoked (called) from JavaScript code
• Automatically (self invoked)

function myFunction(){
//do
}

<button onclick="myFunction()">Click Me!</button>

myFunction();
Function Return
When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to


execute the code after the invoking statement.

// Function is called, the return value will end up in x


let x = myFunction(4, 3);

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.

If the function was invoked from a statement, JavaScript will "return" to


execute the code after the invoking statement.

// Function is called, the return value will end up in x


let x = myFunction(4, 3);

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.

Car object example:


Variables and Objects
JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";

Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named car:

const car = {type:"Fiat", model:"500", color:"white"};


JavaScript Object Definition
Using an Object Literal:

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

const person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue“
};

const person = {};


person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
JavaScript Object Definition
Using the new Keyword:

const person = new Object();


person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
JavaScript Object Definition
Using the Object Constructor:

function Person(firstName, lastName, age, eyeColor) {


this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.eyeColor = eyeColor;
}

const person1 = new Person("John", "Doe", 30, "blue");


const person2 = new Person("Jane", "Doe", 29, “brown");

Person.nationality = "English"; //will not add a property to the constructor


person1.nationality = "English"; //adds a property to the object person1 not to the Person
Constructor

Person.prototype.nationality = "English"; //adds a property to the Object Constructor


Accessing Object Properties
You can access object properties in two ways:

• 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.

In JavaScript, almost "everything" is an object.


• Objects are objects
• Maths are objects
• Functions are objects
• Dates are objects
• Arrays are objects
• Maps are objects
• Sets are objects
All JavaScript values, except primitives, are objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
A primitive data type is data that has a primitive value.

JavaScript defines 7 types of primitive data types:


• string
• number
• boolean
• null
• undefined
• symbol
• bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of
3.14.
JavaScript Objects are Mutable
Objects are mutable: They are addressed by reference, not by value.

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.

In JavaScript, there are two kinds of loops:


• for. Loops through a block of code a specified number of times
• while. Loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should
run.

The syntax is as follows:

for (i = 0; i <= 5; i++){


//execute code while 'i' is less than o equal to 5
document.write("The number is " + i);
document.write("<br />");
}
The while Loop
The while loop loops through a block of code a specified number of times or
while
a specified condition is true.

The syntax is as follows:

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.

The syntax is as follows:

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.

for (let i = 0; i < 10; i++) {


if (i === 3) { break; }
text += "The number is " + i + "<br>";
}

for (let i = 0; i < 10; i++) {


if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

• An HTML web page has finished loading


• An HTML input field was changed
• An HTML button was clicked

<element event="some JavaScript">


JavaScript Events
In the following example, an onclick attribute (with code), is added to a
<button> element:

<button onclick="document.getElementById('demo').innerHTML = Date()">The time


is?</button>
<button onclick="this.innerHTML = Date()">The time is?</button>
Common HTML Events

Click Link below for more!


www.w3schools.com/js/js_events.asp
JavaScript Event Handlers
Event handlers can be used to handle and verify user input, user actions, and
browser actions:
• Things that should be done every time a page loads
• Things that should be done when the page is closed
• Action that should be performed when a user clicks a button
• Content that should be verified when a user inputs data
• And more ...

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:

• The HTML elements as objects


• The properties of all HTML elements
• The methods to access all HTML elements
• The events for all HTML elements

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>

The getElementById Method


• The most common way to access an HTML element is to use the id of the element.
• In the previous example the getElementById method used id="demo" to find the element.

The innerHTML Property


• The easiest way to get the content of an element is by using the innerHTML property.
• The innerHTML property is useful for getting or replacing the content of HTML
elements.
JavaScript - HTML DOM Document
Finding HTML Elements
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are several ways to do
this:

• Finding HTML elements by id


• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections
Finding HTML Elements
Finding HTML Element by Id

const element = document.getElementById("intro");

Finding HTML Elements by Tag Name

const element = document.getElementsByTagName("p");

const x = document.getElementById("main");
const y = x.getElementsByTagName("p");
Finding HTML Elements
Finding HTML Elements by Class Name

const x = document.getElementByClassName("intro");

Finding HTML Elements by CSS Selectors

const x = document.querySelectorAll("p.intro");
JavaScript - HTML DOM
Document

let x = document.getElementById("demo") let x = document.getElementById("demo")

x.src = "landscape.jpg"; x.style.border = "1px solid black";


x.setAttribute("src", "landscape.jpg"); x.style.padding = "30px";
JavaScript - HTML DOM
Document
JavaScript - HTML DOM
Document
Consider the following example:

let container = document.getElementById("container");


let newHeading = document.createElement("h1");
let otherHeading = document.createElement("h1");

newHeading.innerHTML = "I am heading!";


otherHeading.innerHTML = "I am the other Heading!";

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

Visit link below for more HTML Objects


https://www.w3schools.com/js/js_htmldom_document.asp
JavaScript Form Validation
Validate Form – Field Empty <!DOCTYPE html>
<html>
<!DOCTYPE html>
<html> <body>
<head> <h2>JavaScript Validation</h2>
<script>
function validateForm() { <form>
let x = document.forms["myForm"]["fname"].value; <input type="text" name="fname" required>
if (x == "") {
alert("Name must be filled out"); <input type="submit" value="Submit">
return false; </form>
}
} </body>
</script> </html>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" onsubmit="return
validateForm()">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
JavaScript Form Validation
Validate Form – Numeric Input

<!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.

Typical validation tasks are:

• has the user filled in all required fields?


• has the user entered a valid date?
• has the user entered text in a numeric field?
• Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been sent to
the server.

Client side validation is performed by a web browser, before input is sent to a


web server.
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and
useful.

Typical validation tasks are:

• has the user filled in all required fields?


• has the user entered a valid date?
• has the user entered text in a numeric field?
• Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many


different ways.

Server side validation is performed by a web server, after input has been sent to
the server.

Client side validation is performed by a web browser, before input is sent to a


web server.
HTML Constraint Validation
HTML5 introduced a new HTML validation concept called constraint
validation.

HTML constraint validation is based on:

• Constraint validation HTML Input Attributes


• Constraint validation CSS Pseudo Selectors
• Constraint validation DOM Properties and Methods
HTML Constraint Validation
HTML Constraint Validation
JavaScript HTML DOM Animation
<!DOCTYPE html>
<html>
<style>
#container { width: 400px; height: 400px; position: relative; background: yellow; }
#animate { width: 50px; height: 50px; position: absolute; background: red; }
</style>
<body>
<h2>My First JavaScript Animation</h2>
<button onclick="myMove()">Click Me</button><br>
<div id="container">
<div id="animate">
</div>
</div>
<script>
<!-- animation code here -->
</script>
</body>
</html>
Animation Code
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
DOM Event Listener
The addEventListener() method attaches an event handler to the specified element.
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 add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup,
for better readability and allows you to add event listeners even when you do not control the
HTML markup.

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);

You can add events of different types to the same element:

element.addEventListener("mouseover", myFunction);
element.addEventListener("click", mySecondFunction);
element.addEventListener("mouseout", myThirdFunction);
Activity:
Modify the code below to accomplish the
following objectives:

 Change the text content of paragraph with id="text"


when the button is clicked! <!DOCTYPE html>
 Set the size and color of the division with id="colorBox". <html>
 Change to color of the div using: <head>
 onmouseover (mouse over the element event) <title>DOM Events Lab</title>
 onmouseout (mouse outside the element event) <style>
 Add another paragraph and append to div /* Add your CSS styles here */
when the button is clicked! </style>
</head>
<body>
Note: use addEventListener method to accomplish the <h1>DOM Events Laboratory Activity</h1>
following objectives <button id="myButton">Click Me!</button>
<p id="text">Original Text</p>
<div id="colorBox"></div>
<script></script>
</body>
</html>

You might also like