This document provides an introduction to JavaScript and covers topics such as:
- JavaScript allows for interactivity on web pages by manipulating the browser and reacting to user actions.
- JavaScript code is embedded within HTML pages and executed on the client-side by the browser.
- Common JavaScript concepts covered include variables, functions, scope, events, and form validation.
- JavaScript can be used to validate user input, perform calculations, and modify the DOM in response to events.
3. Introduction to Java Script
Browsers have limited functionality
Text, images, tables, frames
JavaScript allows for interactivity
Browser/page manipulation
Reacting to user actions
A type of programming language
Easy to learn
Developed by Netscape
5. Embedded within HTML page
View source
Executes on client
Fast, no connection needed once loaded
Simple programming statements combined with HTML
tags
Interpreted (not compiled)
No special tools required
How Does It Work?
6. •Special syntax to learn
•Learn the basics and then use other
people's (lots of free sites)
•Write it in a text editor, view results in
browser
•You need to revise your HTML
•You need patience and good eyesight
Learning JavaScript
7. Why Study JavaScript?
JavaScript is one of the 3 languages all web
developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
10. JavaScript Statements
HTML written
inside JavaScript
<html>
<head><title>My Page</title></head>
<body>
<p>
<a href="myfile.html">My Page</a>
<br />
<a href="myfile.html"
onMouseover="window.alert('Hello');">
My Page</A>
</p>
</body>
</html>
11. JavaScript outputs
JavaScript can "display" data in different ways:
Writing into an HTML element, using innerHTML.
Writing into the HTML output using document.write().
Writing into an alert box, using window.alert().
Writing into the browser console, using console.log().
12. Using innerHTML
To access an HTML element, JavaScript can use the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the HTML content:
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
17. JavaScript Where To
•In HTML, JavaScript code must be inserted between <script> and
</script> tags.
•Scripts can be placed in the <body>, or in the <head> section of an
HTML page, or in both.
•External JavaScript External file: myScript.js
Ex:
function myFunction()
{
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
<script src="myScript.js"></script>
18. JavaScript Variables
JavaScript variables are containers for storing data values.
Example
var x = 5;
var y = 6;
var z = x + y;
The general rules for constructing names for variables (unique
identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _ (but we will not use it in this tutorial)
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as names
19. Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is called "declaring" a variable.
You declare a JavaScript variable with the var keyword:
var carName;
After the declaration, the variable has no value. (Technically it has
the value of undefined)
To assign a value to the variable, use the equal sign:
carName = "Volvo";
20. Declaring (Creating) JavaScript Variables
Example
<p id="demo"></p>
<script>
var carName = "Volvo";
document.getElementById("demo").innerHTML = carName;
</script>
21. 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).
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
}
22. JavaScript Functions
Function parameters are listed inside the parentheses () in the function
definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
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)
23. JavaScript Functions
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.
•Functions often compute a return value.
•The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
24. JavaScript Functions
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.
•Functions often compute a return value.
•The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
var x = myFunction(4, 3); // Function is called, return value will end up in x
function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
25. JavaScript Functions
The () Operator Invokes the Function
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Accessing a function without () will return the function definition instead of the function result:</p>
<p id="demo"></p>
<script>
function toCelsius(f)
{
return (5/9) * (f-32);
}
document.getElementById("demo").innerHTML = toCelsius;
</script>
</body>
</html>
26. JavaScript Functions
Output:
Accessing a function without () will return the function definition instead of the
function result:
function toCelsius(f) { return (5/9) * (f-32); }
27. JavaScript Scope
Scope determines the accessibility (visibility) of variables.
In JavaScript there are two types of scope:
•Local scope
•Global scope
JavaScript has function scope: Each function creates a new
scope.
28. JavaScript Scope(cont..)
Local JavaScript Variables:
Variables declared within a JavaScript function,
become LOCAL to the function.
Local variables have local scope: They can only be
accessed within the function.
Example
// code here can not use carName
function myFunction() {
var carName = "Volvo";
// code here can use carName
}
29. Local Variables: Example Program
<!DOCTYPE html>
<html>
<body>
<p>The local variable carName cannot be accessed from code outside the function:</p>
<p id="demo"></p>
<script>
myFunction();
document.getElementById("demo").innerHTML =
"The type of carName is " + typeof carName;
function myFunction() {
var carName = "Volvo";
}
</script>
</body>
</html>
30. JavaScript Scope(cont..)
Global JavaScript Variables
•A variable declared outside a function, becomes GLOBAL.
•A global variable has global scope: All scripts and
functions on a web page can access it.
Example
var carName = " Volvo";
// code here can use carName
function myFunction()
{
// code here can use carName
}
31. Example code:<!DOCTYPE html>
<html>
<body>
<p>A GLOBAL variable can be accessed from any script or function.</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
myFunction();
function myFunction()
{
document.getElementById("demo").innerHTML =
"I can display " + carName;
}
</script>
</body>
32. Automatically Global
If you assign a value to a variable that has not been declared, it will
automatically become a GLOBALvariable.
This code example will declare a global variable carName, even if
the value is assigned inside a function.
Example
myFunction();
// code here can use carName
function myFunction() {
carName = "Volvo";
}
33. JavaScript Events
HTML events are "things" that happen to HTML elements.
When JavaScript is used in HTML pages, JavaScript can "react" on
these events.
HTML 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
34. JavaScript Events
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added
to a button element:
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
35. JavaScript Events
Common HTML Events
Here is a list of some common HTML events:
EventDescription
•Onchange An HTML element has been changed
•Onclick The user clicks an HTML element
•Onmouseover The user moves the mouse over an HTML element
•Onmouseout The user moves the mouse away from an HTML
element
• onkeydown The user pushes a keyboard key
•Onload The browser has finished loading the page
36. JavaScript Events
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..etc.
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..etc..
37. JavaScript Events
•Onclick The user clicks an HTML element
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The
time is?</button>
<p id="demo"></p>
</body>
</html>
38. JavaScript Events
•Onclick The user clicks an HTML element
<!DOCTYPE html>
<html>
<body>
<button onclick="document.getElementById('demo').innerHTML=Date()">The
time is?</button>
<p id="demo"></p>
</body>
</html>
39. JavaScript Events
Onkeydown and onkeyup The user clicks an HTML element
(example 1)
<!DOCTYPE html>
<html>
<body>
<p>Press and hold down a key inside the text field to set a red background color. Release the key to
set a green background color.</p>
<input type="text" id="demo" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
<script>
function keydownFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
function keyupFunction() {
document.getElementById("demo").style.backgroundColor = "green";
}
</script>
40. JavaScript Events
Onkeydown and onkeyup The user clicks an HTML element
(example 1)
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to attach a "keydown" event to an input element.</p>
<p>Press a key inside the text field to set a red background color.</p>
<input type="text" id="demo">
<script>
document.getElementById("demo").addEventListener("keydown", myFunction);
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
</script>
</body>
</html>
41. JavaScript Events
onmousedown Event
The onmousedown event occurs when a user presses a mouse
button over an element.
Tip: The order of events related to the onmousedown event (for
the left/middle mouse button):
•onmousedown
•onmouseup
•onclick
42. JavaScript Events
onmousedown Event
<!DOCTYPE html>
<html>
<body>
<p>This example uses the addEventListener() method to attach a "mousedown" and "mouseup" event to a p element.</p>
<p id="demo">Click me.</p>
<script>
document.getElementById("demo").addEventListener("mousedown", mouseDown);
document.getElementById("demo").addEventListener("mouseup", mouseUp);
function mouseDown() {
document.getElementById("demo").innerHTML = "The mouse button is held down.";
}
function mouseUp() {
document.getElementById("demo").innerHTML = "You released the mouse button.";
}
</script>
</body>
</html>
43. JavaScript Form Validation
HTML form validation can be done by JavaScript.
If a form field (fname) is empty, this function alerts a message, and
returns false, to prevent the form from being submitted:
JavaScript Example
function validateForm()
{
var x = document.forms["myForm"]["fname"].value;
if (x == "")
{
alert("Name must be filled out");
return false;
}
}
44. Form Validation program
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php"
onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
45. Form Validation program
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Can Validate Input</h2>
<p>Please input a number between 1 and 10:</p>
<input id="numb">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
<script>
function myFunction() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("numb").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
46. Automatic HTML Form Validation
HTML form validation can be performed automatically by the browser:
If a form field (fname) is empty, the required attribute prevents this form from
being submitted:
<!DOCTYPE html>
<html>
<body>
<form action="/action_page.php" method="post">
<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>
<p>If you click submit, without filling out the text field,
your browser will display an error message.</p>
</body>
</html>
47. 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.
48. 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
49. Constraint Validation HTML Input Attributes
Attribute Description
disabled Specifies that the input element should be disabled
max Specifies the maximum value of an input element
min Specifies the minimum value of an input element
pattern Specifies the value pattern of an input element
required Specifies that the input field requires an element
type Specifies the type of an input element
50. Example 1
<!DOCTYPE html>
<html>
<body>
<h2>The readonly Attribute</h2>
<p>The readonly attribute specifies that the input field is read only (cannot be
changed):</p>
<form action="">
First name:<br>
<input type="text" name="firstname" value ="John" readonly>
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
</body>
</html>
51. Example 2
<!DOCTYPE html>
<html>
<body>
<h2>The disabled Attribute</h2>
<p>The disabled attribute specifies that the input field is disabled:</p>
<form action="">
First name:<br>
<input type="text" name="firstname" value ="John" disabled>
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
</body>
</html>