Introduction to JavaScript
Instructor : Dr Farzana Jabeen
Quick Recap
Why JavaScript?
• HTML to define the
content of web pages
• CSS to specify the
layout of web pages
• JavaScript to program
the behavior of web
pages
• https://www.w3schools
.com/js/
Document Object Model
• An object could be anything (e.g. a Web page)
• Objects perform methods (show an image)
• Objects have properties which can be
modified
– Image
• Height/Width
• Manipulate properties with JavaScript
JavaScript Can Change HTML Content
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML
content.</p>
<button type="button"
onclick="document.getElementById('demo').
innerHTML = 'Hello JavaScript!'">
Click Me!</button>
</body>
</html>
Find an HTML element by its id
JavaScript Can Change HTML Attributes
<h1>JavaScript Can Change Images</h1>
<img id="myImage" onclick="changeImage()"
src="pic_bulboff.gif" width="100"
height="180">
<p>Click the light bulb to turn on/off the
light.</p>
<script>
function changeImage() {
var image =
document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
</script>
JavaScript Can Change HTML Styles (CSS)
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the
style of an HTML element.</p>
<script>
function myFunction() {
var x =
document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
</script>
<button type="button"
onclick="myFunction()">Click Me!</button>
JavaScript Can Validate Data
<h1>JavaScript Can Validate Input</h1>
<p>Please input a number between 1 and 10:</p>
<input id="numb" type="number">
<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>
Javascript Variables
• All JavaScript variables must be identified with unique names.
• These unique names are called identifiers.
• Identifiers can be short names (like x and y), or more
descriptive names (age, sum, totalVolume).
• 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
Variables and Data Types
• Numbers
– Integer and floating-point numbers.
• Booleans
– True or false.
• Strings
– Anything surrounded by “” (double quotes) or ‘’ (single quotes)
e.g. “My String” = ‘My String’
• Object
– myObj = new Object();
• null
– Not the same as zero - no value at all.
• Undefined
– The Variable has been created but no value has been assigned to it
Operators
• Arithmetic
+,-,*,/,%,--,++
• Comparison
==, !=, >, >=, <, <=
• Boolean
&&, ||, !
Coercion
• A variable of one type can be used as if it were
another.
• If there's a conflict, javascript doesn't produce
an exception
– string+number goes to strings
– boolean+string goes to strings
– number+boolean goes to numbers
– Explicit conversions
• string to an integer, use the parseInt() method.
• string to a number, use the parseFloat() method.
JavaScript Arithmetic
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>Add 5 + 2 + 3, and display the result:</p>
<p id="demo"></p> What will be the output here?
<script>
var x = 5 + 2 + 3;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Today’s Lecture
JavaScript Arithmetic
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>Add “Jhon" + " " + “Smith":</p>
<p id="demo"></p> What will be the output here?
<script>
var x = “Jhon" + " " + “z";
document.getElementById("demo").innerHTML = x;
</script> JavaScript Variables
Add “Jhon”+” “+”Smith”
</body> Jhon Z
</html>
JavaScript Arithmetic
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p id="demo"></p>
<script> What will be the output here?
var x = "5" + 2 + 3;
var y = 5 + 2 + "3";
var z = 5 + "2" + 3;
document.getElementById("demo").innerHTML += x+"<br/>";
document.getElementById("demo").innerHTML += y+"<br/>";
document.getElementById("demo").innerHTML += z;
</script>
</body>
</html>
Statements
• Conditionals
– if(x < 0){
alert(“x is negative”);
}
else{
alert(“x is positive”);
}
– switch(favoriteProf){
case “Jhon”:
//statements;
break;
case “Jhon Smith”:
//statements;
break;
default:
statement;
}
Statements
• Loops
– for(var i =0; i < myArray.length;i++){
document.write(i);
}
– do
{ statements;}
while (condition)
– while(condition){
statements;
}
Functions
• The function is a set of statements that perform
some specific piece of work.
• JS Function
function funcName(argument1,argument2,etc) {
statements;
}
• Example:
function foo(myString){ // this is function definition
document.write(myString);
}
foo(“Computers are fun”); // calling the function
Function Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert(“The aliens have landed!!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()">
</form>
</body>
</html>
Events
• Events are actions that can be detected by JavaScript.
• Every element on a web page has certain events which can trigger
JavaScript functions.
• For example, we can use the onClick event of a button element to
indicate that a function will run when a user clicks on the button.
We define the events in the HTML tags.
• Examples of events:
– A mouse click
– A web page loading or an image loading
– Mousing over a hot spot on the web page
– Selecting an input box in an HTML form
– Submitting an HTML form
– A keystroke
Event Handlers
• JavaScript events are placed inside HTML Tags
• Examples:
onclick onmousedown
onload ondblclick
onunload onkeypress
onmouseout onkeydown
onmouseover onkeyup
onmouseup onselect
onchange onsubmit
onfocus onblur
Real Life Examples
• Form Validation
Create function to run on form’s onSubmit event
<form id="myForm" action="#" onsubmit="return validate()“
method="get" >
<input type="text" name="firstName" id=“fName“ />
<input type=“text" name=“lastName" id=“lName“ />
<input type="submit" />
</form>
Real Life Examples
• Form Validation
function validate()
{
if(myform[“fname"].value==""){
alert("You must enter your first name");
myform[“fname"].focus();
return false;
}
if(myform[“lname"].value==""){
alert("You must enter your last name");
myform[“lname"].focus();
return false;
}
return true;
}
Real Life Examples
Other ways to access a form
document.forms[0].elements[0]
gets the first form and first element of the form
document.forms[“formName”].elements[“elemen
tName”]
document.formName.elementName
Image Rollover
• Swap Images
– On mouse over event swap the image
– On mouse out event restore the image
• Code
<html>
<head>
</head>
<body>
<a href="#" onmouseover=“myimage.src=‘image2.jpg'“
onmouseout=“myimage.src=‘image1.jpg'">
<img src=“image1.jpg" id=“myimage" name=“myimage“ width=“130" height=“15" /></a>
</body>
</html>
JavaScript Objects
• JavaScript is an Object Oriented Programming
(OOP) language. An OOP language allows you
to define your own objects and make your
own variable types.
• Note that an object is just a special kind of
data. An object has properties and methods.
JavaScript Objects
• To declare an object
var myObj = new Object();
• To set properties
myObj.name = “Alex”
JavaScript Objects
• Properties
– Properties are the values associated with an object.
– In the following example we are using the length property of the
String object to return the number of characters in a string:
<Html>
<Head> <Title> My Page</Title>
<script type="text/javascript">
var txt="Hello Class!“;
document.write(txt.length);
</script>
</Head>
<Body> Hello Class </Body>
</Html>
The output of the code above will be: 12
Matching
<html>
<body>
<script type="text/javascript">
var str="Hello world!"
document.write(str.match("world") + "<br />")
document.write(str.match("World") + "<br />")
document.write(str.match("worlld") + "<br />")
document.write(str.match("world!"))
</script>
</body>
</html>
Output: world
null
null
world!
Replace
<html>
<body>
<script type="text/javascript">
var str="Visit SEECS!"
document.write(str.replace(“SEECS","NUST"))
</script>
</body>
</html>
Output: Visit NUST!
Date Object
• The Date object is used to work with dates and times.
• Examples
– Return today's date and time
How to use the Date() method to get today's date.
– get Time()
Use getTime() to calculate the years since 1970.
– setFullYear()
How to use setFullYear() to set a specific date.
– getDay()
Use getDay() and an array to write a weekday, and not just a number.
– Display a clock
How to display a clock on your web page.
For a complete list of Date Object methods:
http://www.w3schools.com/jsref/jsref_obj_date.asp
Getting the date
<Html>
<Head> <Title> My Page</Title>
<script type="text/javascript">
var d = new Date()
document.write(d.getDate() + "/")
document.write((d.getMonth() + 1) + "/")
document.write(d.getFullYear())
</script>
</Head>
</Html>
OUTPUT: 6/3/2023
Math Objects
• The Math object allows you to perform common
mathematical tasks.
• Examples
– round()
How to use round().
– random()
How to use random() to return a random number between 0
and 1.
– max()
How to use max() to return the number with the highest value
of two specified numbers.
– min()
How to use min() to return the number with the lowest value of
two specified numbers.
Getting a random number
• The following code gets a random floating-
point number between 0 and 1:
• <script type="text/javascript">
document.write(Math.random())
</script>
0.728762788388911
Getting a random integer
• The following code gets a random integer
between 1 and 10:
<script type="text/javascript">
var max = 10;
number=Math.random()*max + 1;
document.write(Math.floor(number));
</script>
5
Text Literals
• Double and Single Quotes
• Escape Sequences begin with a \
– \b is backspace, \n is newline, \r is CR
– \’ is single quote (so you can use it in a string as a
literal)
– \\ is backslash
Math
• Standard Math functions supported (+, -, *, /,
etc.)
• Use parseInt() or parseFloat() method to treat
variables as numbers
var x = prompt ("What Year Is It?");
var y = prompt ("What Year Were You Born?”);
document.write ("You're " + (parseInt(x)-
parseInt(y)) + " years old");
• Precedence is important!
Array literals
• You don’t declare the types of variables in JavaScript
• JavaScript has array literals, written with brackets and
commas
– Example: color = ["red", "yellow", "green", "blue"];
– Arrays are zero-based: color[0] is "red"
• If you put two commas in a row, the array has an
“empty” element in that location
– Example: color = ["red", , , "green", "blue"];
• color has 5 elements
– However, a single comma at the end is ignored
• Example: color = ["red", , , "green", "blue”,]; still has 5 elements
Four ways to create an array
• You can use an array literal:
– var colors = ["red", "green", "blue"];
• You can use new Array() to create an empty array:
– var colors = new Array();
– You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(n) with a single numeric argument to create an
array of that size
– var colors = new Array(3);
– You can add elements to the array later:
colors[0] = "red"; colors[2] = "blue"; colors[1]="green";
• You can use new Array(…) with two or more arguments to create an array
containing those values:
– var colors = new Array("red","green", "blue");
The length of an array
• If myArray is an array, its length is given by myArray.length
• Array length can be changed by assignment beyond the
current length
– Example:
var myArray = new Array(5);
myArray[10] = 3;
• Arrays are sparse, that is, space is only allocated for
elements that have been assigned a value
– Example:
myArray[50000] = 3;
– But indices must be between 0 and 232-1
Array functions
• If myArray is an array,
– myArray.sort() sorts the array alphabetically
– myArray.sort(function(a, b) { return a - b; }) sorts
numerically
– myArray.reverse() reverses the array elements
– myArray.push(…) adds any number of new elements to
the end of the array, and increases the array’s length
– myArray.pop() removes and returns the last element of
the array, and decrements the array’s length
– myArray.toString() returns a string containing the values
of the array elements, separated by commas
Prepare Quiz with 6 questions regarding array sorting and set timer to 1
minute to solve it. when times up show the final score. Use Java script,
Html and CSS.
Hint : use Array, Forms
CLASS ACTIVITY
JS Scope, JS Maps, Arrow Functions, JS Strict Mode, JS Destructuring
READING TASKS