Final Java Script
Final Java Script
By Sangita M. Jaybhaye
JavaScript in External File
• HTML File
<html>
<head>
<script type="text/javascript" src="filename.js" >
</script>
</head>
<body> ....... </body>
</html>
1.<script>
2.var x = 10;
•
3.var y = 20;
4.var z=x+y;
5.document.write(z);
6.</script>
JavaScript Variables
• Variables are declared with the var keyword
E.g
• 4 Ways to Declare a JavaScript Variable:
• Using var
• Using let
• Using const
• Using nothing
• Example 2
1. <script>
2. var pow=new Function("num1","num2","return Math.p
ow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
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).
<!DOCTYPE html>
Output:
<html>
<body>
JavaScript Functions
<h2>JavaScript Functions</h2> This example calls a
<p>This example calls a function which performs a calculation, and function which
returns the result:</p> performs a
<p id="demo"></p> calculation, and
<script> returns the result:
function myFunction(p1, p2) {
return p1 * p2;
12
}
document.getElementById("demo").innerHTML = myFunction(4, 3);
</script>
</body>
</html>
JavaScript Output
• JavaScript Display Possibilities
• JavaScript can "display" data in different ways:
• Using document.write() after an HTML document is loaded, will delete all existing
HTML:
• <!DOCTYPE html>
• <html>
• <body>
• <h1>My First Web Page</h1>
• <p>My first paragraph.</p>
• <button type="button" onclick="document.write(5 + 6)">Try
it</button>
• </body>
• </html>
• The document.write() method should only
be used for testing.
• <!DOCTYPE html>
• <html>
• <body>
• <h2>My First Web Page</h2>
• <p>My first paragraph.</p>
• <script>
• alert(5 + 6);
• </script>
• </body>
• </html>
Using console.log()
• For debugging purposes, you can call the console.log() method in the
browser to display data.
• <!DOCTYPE html>
• <html>
• <body>
• <h2>Activate Debugging</h2>
• <p>F12 on your keyboard will activate debugging.</p>
• <p>Then select "Console" in the debugger menu.</p>
• <p>Then click Run again.</p>
• <script>
• console.log(5 + 6);
• </script>
• </body>
• </html>
Standard Popup Boxes
• Alert box with text and [OK] button
• Just a message shown in a dialog box:
alert("Some text here");
• Confirmation box
• Contains text, [OK] button and [Cancel] button:
confirm("Are you sure?");
• Prompt box
• Contains text, input field with default value:
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 =
parseInt(document.mainForm.textBox1.value);
value2 =
parseInt(document.mainForm.textBox2.value);
sum = value1 + value2;
document.mainForm.textBoxSum.value = sum; 35
}
</script>
</head>
Sum of Numbers – Example (2)
sum-of-numbers.html
(cont.)
<body>
<form name="mainForm">
<input type="text" name="textBox1" />
<br/>
<input type="text" name="textBox2" />
<br/>
<input type="button" value="Process"
onclick="javascript: calcSum()" />
<input type="text" name="textBoxSum"
readonly="readonly"/>
</form>
</body>
36
</html>
JavaScript Objects
• A javaScript object is an entity having state and behavior
(properties and method).
• For example: car, pen, bike, chair, glass, keyboard, monitor
etc.
• JavaScript is an object-based language. Everything is an
object in JavaScript.
• JavaScript is template based not class based. Here, we don't
create class to get the object. But, we direct create objects.
• JavaScript 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 a variable named car:
• const car = {type:"Fiat", model:"500", color:"white"};
JavaScript Objects
• The values are written as name:value pairs (name and value
separated by a colon).
• Example
• const person = {
• firstName: "John",
• lastName: "Doe",
• age: 50,
• eyeColor: "blue"
• };
Object Properties
9.</script>
Defining method in JavaScript
Object
1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. this.changeSalary=changeSalary;
7. function changeSalary(otherSalary){
8. this.salary=otherSalary;
9. }
10. }
11. e=new emp(103,"Sonoo Jaiswal",30000);
12. document.write(e.id+" "+e.name+" "+e.salary);
13. e.changeSalary(45000);
14. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
15.</script>
JavaScript Arrays
• JavaScript array is an object that represents a collection of
similar type of elements.
• There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1.<script>
2.var i;
3.var emp = new Array();
4.emp[0] = "Arun";
5.emp[1] = "Varun";
6.emp[2] = "John";
7. for (i=0;i<emp.length;i++){
8.document.write(emp[i] + "<br>");
9.}
10.</script>
JavaScript array constructor
(new keyword)
1.<script>
2.var emp=new Array("Jai","Vijay","Smith");
3.for (i=0;i<emp.length;i++){
4.document.write(emp[i] + "<br>");
5.}
6.</script>
JavaScript Arrays
Output:
JavaScript Arrays
<!DOCTYPE html> TATA,Volvo,BMW
<html>
<body>
<h2>JavaScript Arrays</h2>
<p id="demo"></p>
<script>
const cars = [“TATA”, "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
</body>
</html>
Events
<!DOCTYPE html>
.
<html>
<body> The time is?
<h2>JavaScript HTML Events</h2> Mon Feb 28 2022
<p>Click the button to display the date.</p> 14:55:15 GMT+0530
<button onclick="displayDate()">The time is?</button> (India Standard Time)
<script>
function displayDate() {
document.getElementById("demo").innerHTML =
Date();
}
</script>
<p id="demo"></p>
</body>
</html>
JavaScript Arrays
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2> JavaScript Arrays
<p>JavaScript array elements are accessed JavaScript array
using numeric indexes (starting from 0).</p> elements are
<p id="demo"></p> accessed using
numeric indexes
<script>
(starting from 0).
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel"; Opel,Volvo,BMW
document.getElementById("demo").innerHTM
L = cars;
</script>
</body>
</html>
JavaScript Object Properties
</body>
</html>
Variable Scope
• Global variables :
• Declaring a variable outside the function makes it a global
variable.Variable is accessed everywhere in the document.
• E.g.
• Accessing Object Properties
• You can access object properties in two ways:
1.objectName.propertyName
• or
2. objectName["propertyName"]
Example1
• person.lastName;
Creating an Array
• Using an array literal is the easiest way to create a JavaScript Array.
• Syntax:
• const array_name = [item1, item2, ...];
• It is a common practice to declare arrays with the const keyword.
• Learn more about const with arrays in the chapter: JS Array Const.
• Example
• const cars = ["Saab", "Volvo", "BMW"];
• Spaces and line breaks are not important. A declaration can span multiple
lines:
• Example
• const cars = [
• "Saab",
• "Volvo",
• "BMW"
• ];
Creating an Array
• You can also create an array, and then provide the elements:
Example
const cars = [];
cars[0]= “TATA";
cars[1]= “Audi";
cars[2]= "BMW";
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to
it:
• Example
• const cars = new Array(“TATA", “Audi", "BMW");
Converting Arrays to Strings
• Example
Result:
• Banana,Orange,Apple,Mango
JavaScript Array concat()
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The concat() Method</h2>
<p>The concat() method concatenates (joins) two or more arrays:</p>
<p id="demo"></p>
<script>
const arr1 = ["A", "B"];
const arr2 = ["C", "D", "E"];
const children = arr1.concat(arr2);
document.getElementById("demo").innerHTML = children;
</script>
</body>
</html>
JavaScript Array concat()
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The concat() Method</h2>
<p>The concat() method concatenates (joins) two or more arrays:</p>
<p id="demo"></p>
<script>
const arr1 = ["A", "B"];
const arr2 = ["C", "D", "E"];
const arr3 = ["F"];
const children = arr1.concat(arr2,arr3);
document.getElementById("demo").innerHTML = children;
</script>
</body>
</html>
JavaScript Array length
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The length Property</h2>
<p>The length property sets or returns the number of elements in an
array.</p>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
document.getElementById("demo").innerHTML = length;
</script>
</body>
</html>
join() method
• The join() method also joins all array elements into a string.
• It behaves just like toString(), but in addition you can specify the
separator:
• Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
• Result:
Banana * Orange * Apple * Mango
Popping and Pushing
• Example
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.pop();
pop() method
• The pop() method returns the value that was "popped out":
Example
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
• let fruit = fruits.pop();
JavaScript Sorting Arrays
• Sorting an Array
• The sort() method sorts an array alphabetically:
• Example
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.sort();
• Reversing an Array
• The reverse() method reverses the elements in an array.
• You can use it to sort an array in descending order:
• Example
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
• fruits.sort();
• fruits.reverse();
Numeric Sort
By default, the sort() function sorts values as strings.
• This works well for strings ("Apple" comes before "Banana").
• However, if numbers are sorted as strings, "25" is bigger than
"100", because "2" is bigger than "1".
• Because of this, the sort() method will produce incorrect result
when sorting numbers.
• You can fix this by providing a compare function:
• const points = [40, 100, 1, 5, 25, 10];
• points.sort(function(a, b){return a - b});
Reverse an array using
JavaScript
1.Using the reverse method
• As the name suggests, this method reverses the
order of array elements by modifying the existing
array.
Syntax: array.reverse()
Example:
arr = [1,2,3,4]; arr.reverse();
console.log(arr); //Output: [ 4, 3, 2, 1 ]
2.Using a decrementing
For Loop
arr = [1, 2, 3, 4];
arr1 = [];
for (let i = arr.length - 1; i >= 0; i--) {
arr1.push(arr[i]);
}
console.log(arr1);
//Output: [4, 3, 2, 1]
<html> <head>
<script>
function validateForm() {
if(document.myForm.name.value.match(/^[A-Za-z]+$/)) { }
else {
alert("Please Characters only");
document.myForm.name.focus();
return false; }
if(document.myForm.phone.value.match(/^[0-9]+$/)) {
message = "<br>NAME:" + document.myForm.name.value;
message += "<br>ADDRESS: " + document.myForm.address.value;
message += "<br>GENDER: " + document.myForm.G.value ;
message += "<br>PHONE: " + document.myForm.phone.value ;
message += "<br>DOB: " + document.myForm.DOB.value ;
message += "<br>EMail-Id: " + document.myForm.email.value ;
document.write(message); }
else {
alert('Please input numeric characters only');
document.myForm.phone.focus();
return false; } }
</script> </head>
HTML Form Validation using JS:
Student Registration Form (Required Field and accepting characters only in Name text box and
digits only in Phone text box)
<body>
<form name="myForm" onsubmit="return validateForm()">
<table border=1 align=center>
<caption><h1> Enquiry Form </h1></caption>
<tr><td>Name</td>
<td><input type="text" name="name" required></td></tr>
<tr><td>Phone No:</td>
<td><input type="text" name="phone" maxlength=10 required></td></tr>
<tr><td>Email</td>
<td><input type="Email" name="email" required></td></tr>
<tr><td>DOB</td>
<td><input type="date" name="DOB" required></td></tr>
<tr><td>Gender</td>
<td><input type="radio" name="G" value="Male" checked>Male
<input type="radio" name="G" value="Female" >Female</td></tr>
<tr><td>Address(Region)</td>
<td><select name="address">
<option> Nashik </option>
<option> Pune </option></select></td></tr>
<tr><td colspan=2 align=center><input type="submit" value="Submit"></td></tr>
</table></form></body></html>
• <!DOCTYPE html>
• <html>
• <body>
• <h1>Display a Telephone Input Field</h1>
• <form action="/action_page.php">
• <label for="phone">Enter a phone
number:</label><br><br>
• <input type="tel" id="phone" name="phone"
placeholder="123-45-678" pattern="[0-9]{3}-[0-9]{2}-[0-
9]{3}" required><br><br>
• <small>Format: 123-45-678</small><br><br>
• <input type="submit">
• </form>
• </body>
• </html>
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<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>
</html>
Example of regular expression
1. /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]
{2,6}$/
2. /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-
Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
3. ('[a-z0-9]+@[a-z]+\.[a-z]{2,3}
Valid and Invalid examples
• Some of the examples of valid email id:
• [email protected]
• [email protected]
• [email protected]
• Some Other Examples of Invalid Email Id
• [email protected] (one on another dots are not
allowed)
• Inownzsite()&@abcd.com (only characters, dash,
underscore, and digits are allowed in the regular expression.)
• Ourwebsiteismne.azbyz.com (here @ symbol is not there)
• [email protected] (Here top-level domain can’t
begin with a dot)
• @youmenandwe.we.net (here it can’t start with @ symbol)
• [email protected] (“.b” is not a valid top-level
domain)email.js
Checkpoints for efficient email
validation in JavaScript code:
• Describe a regular expression to validate an email
address
• If an input value matches regular expressions
• If it matches, sends the alert saying “email
address is valid.”
• If it does not match, send the alert saying, “email
address is invalid.”
Email validation
• [email protected]
• [email protected]
• [email protected]
Example of invalid email id
• mysite.ourearth.com [@ is not present]
[email protected] [ tld (Top Level domain) can not start
with dot "." ]
• @you.me.net [ No character before @ ]
• [email protected] [ ".b" is not a valid tld ]
• [email protected] [ tld can not start with dot "." ]
• [email protected] [ an email should not be start with "."
]
• mysite()*@gmail.com [ here the regular expression only
allows character, digit, underscore, and dash ]
• [email protected] [double dots are not allowed]
JavaScript code to validate
an email id
• function ValidateEmail(mail)
{ if (/^\w+([\.-]?\w+)*@\w+([\.-]?\
w+)*(\.\w{2,3})+
$/.test(myForm.emailAddr.value))
{
return (true)
}
alert("You have entered an invalid email
address!")
return
(false)
}
HTML Code
• <!DOCTYPE html>
• <html lang="en">
• <head>
• <meta charset="utf-8">
• <title>JavaScript form validation - checking email</title>
• <link rel='stylesheet' href='form-style.css' type='text/css' />
• </head>
• <body onload='document.form1.text1.focus()'>
• <div class="mail">
• <h2>Input an email and Submit</h2>
• <form name="form1" action="#">
• <ul>
• <li><input type='text' name='text1'/></li>
• <li> </li>
• <li class="submit"><input type="submit" name="submit" value="Submit"
onclick="ValidateEmail(document.form1.text1)"/></li>
• <li> </li>
• </ul>
• </form>
• </div>
• <script src="email-validation.js"></script>
• </body>
• </html>
JavaScript Code
function ValidateEmail(inputText)
{
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\
w{2,3})+$/;
if(inputText.value.match(mailformat))
{
alert("Valid email address!");
document.form1.text1.focus(); return true;
}
else
{ alert("You have entered an invalid email
address!");
document.form1.text1.focus(); return false;
}
}
What is Responsive Web Design?
• <!DOCTYPE html>
• <html>
• <head>
• <meta name="viewport" content="width=device-width, initial-scale=1.0">
• </head>
• <body>
• <h2>Setting the Viewport</h2>
• <p>This example does not really do anything, other than showing you how
to add the viewport meta element.</p>
• </body>
• </html>
The HTML <video>
Element
• How it Works?
• The controls attribute adds video controls, like play, pause,
and volume.
• It is a good idea to always include width and height attributes.
If height and width are not set, the page might flicker while
the video loads.
• The <source> element allows you to specify alternative video
files which the browser may choose from. The browser will
use the first recognized format.
• The text between the <video> and </video> tags will only be
displayed in browsers that do not support the <video>
element.
• <!DOCTYPE html>
• <html>
• <body>
• <video width="320" height="240" controls>
• <source src="movie.mp4" type="video/mp4">
• <source src="movie.ogg" type="video/ogg">
• Your browser does not support the video tag.
• </video>
• </body>
• </html>
Create an one College Template with video in Background (The
Web Page must be Responsive and the page contains video in
Background)