05 JavaScript v5 Part-2
05 JavaScript v5 Part-2
• 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>
<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>
<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;
– 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>
<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>
<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);
}
</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>
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: 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(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