0% found this document useful (0 votes)
22 views135 pages

WINSEM2024-25 BCSE203E ELA VL2024250504295 2025-02-27 Reference-Material-I

This document provides an overview of client-side processing and scripting with a focus on JavaScript. It covers key concepts such as functions, arrays, the Document Object Model (DOM), and various JavaScript methods and properties for manipulating HTML elements. Additionally, it includes examples and exercises to reinforce understanding of JavaScript programming and its applications in web development.

Uploaded by

amanshaik249a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views135 pages

WINSEM2024-25 BCSE203E ELA VL2024250504295 2025-02-27 Reference-Material-I

This document provides an overview of client-side processing and scripting with a focus on JavaScript. It covers key concepts such as functions, arrays, the Document Object Model (DOM), and various JavaScript methods and properties for manipulating HTML elements. Additionally, it includes examples and exercises to reinforce understanding of JavaScript programming and its applications in web development.

Uploaded by

amanshaik249a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 135

Web Programming

Module - IV
Dr S P Meenakshi
[email protected]
SCOPE
Client side processing and scripting
• Javascript Introduction
• Functions
• Arrays
• DOM
• Built-in objects
• Regular expression
• Exception
• Event handling
• Validation
Scripting Languages
• Scripting languages can perform different actions within a particular runtime
environment.
• Task such as automating code execution, enhancing the functionality of the
parent software, performing configurations, extracting data from data sets,
and others.
• Scripting languages can come about in two ways:
• A runtime environment can introduce its own scripting language, such as
Bash for the GNU operating system or VBA for Microsoft Office applications.
• A runtime environment can adopt an existing scripting language, for
instance, MongoDB’s mongo shell has been built around JavaScript.
• Sometimes it’s the scripting language that exists first and it gives birth to its
own parent platform. i.e Node.js, a backend runtime environment that was
created to allow web developers to use JavaScript not just on the frontend
but also on the backend
Javascript Introduction
• HTML – to define the content of the web pages
• CSS – to specify the layout of the web pages
• Javascript – to program the behaviour of the web pages
What javascript can do
• Change the content of html element
• getElementById – is javascript html method
• Using the method , html element named “demo” content changed
document.getElementById(“demo”).innerHTML=“Change the text”;
• Accepts single and double quotes
• Javascript can change HTML attribute values – image src attribute
change
• <img id=image1 src=“pic_pulboff.gif
style=“height:100px;width=100px;”>
• <button onclick= '
document.getElementById(“image1”).src=“pic_pulbon.gif” '> Turn on
the light</button>
Javascript Introduction
• Javascript can change HTML CSS styles
• document.getElementById(“Demo”).style.fontSize=70px;
• Hidden html elements can be shown using javascript
• <p id=“para1” style=”display:none”> Hidden text </p>
• <input type=button
onclick=document.getElementById(“para1”).style.display=“block”>clickme</
input>
• In html, javascript code is inserted between <script></script> tags
• <script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
Javascript functions and events
• Javascript function is a block of code, that will be executed when it is
called for.
• Functions will be called when an event occurs i.e., button click
• Many Scripts can be placed in a html document
• Scripts can be kept in <head> section or <body> section or both the
sections
Javascript function
• <head>
<script>
function myfunction()
{
document.getElementById(“demo”).innerHTML=“Text change”;
}
</script>
</head>
<body>
<p id=“demo”>Paragraph text</p>
<button type=“button” onclick=“myfunction()”>Click me</button>
</body>
Javascript functions and events
• Function syntax
• function <function name> (<parameter1>,<parameter2> …)
{
<statements>
return <value>;
}
• 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 definition and invocation
• <label for="in1" > Enter Number </label>
<input type="text" id="in1" name="in1" value="8">
<button type=button onclick="avg(in1.value)">click</button>
<script>
function avg(a)
{
let y;
y=(8+8+8+9+10)/a;
document.write(y);
return ;
}
</script>
Javascript functions and events
• Javascript can be kept as external file stored as myscript.js
• function myfunction() {
document.getElementById(“demo”).style.display=“block”;
}
• The external file called using the script tag in the html document
• <script src=myscript.js>
</script>
Javascript functions and events
• External javascripts files cannot contain <script> tag
• Placing scripts in external files separate the html and javascript code
• Separation makes it to more readable and maintainable
• Cached java script also speed up page loads
• To include several scripts to a page, use many script tags
• External script can be referenced using, whole url, with file path,
without file path
• Full url is referenced as
• <script src="https://www.w3schools.com/js/myScript.js"></script>
Javascript Display possibilities
• Javascript can display data in different ways
• Writing into an html element using innerHTML
• Writing into the html document using document.write()
• <script>
document.write(5 + 6);
</script>
• Writing into an alert box using window.alert()
• <script>
• window.alert(5 + 6);
• </script>
• Writing into the browser console, using console.log()
• <script>
console.log(5 + 6);
</script>
Exercise
• Create an MCQ quiz of 10 questions. Every question validate the
response by the user and pop up the result using javascript. Finally
display the result in new page with a designed certificate.
Javascript statement and keywords
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be
executed on a condition
switch Marks a block of statements to be
executed in different cases
for Marks a block of statements to be
executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of
statements
Javascript Variables
• <input type="number" id="in1" value="10">
• <input type="number" id="in2" value="12">
• <button onclick='Displaydocument(in1.value,in2.value)'> Click to display input values </button>
• <script>
• function Displaydocument(a,b)
• {
• let c;
• c=parseInt(a)+parseInt(b);
• document.write(a + "+" + b +"=" + c);
• // document.write(`${a} + ${b} : ${c}`);
• }
• </script>
If,for,switch

statement
if(y<10){
console.log("y less than 10");
}
else
{
console.log("y greater than 10");
}

• for(i=0;i<5;i++)
{
document.write(i);
}

• switch(a)
{
case 5:
console.log(" Case 5");
break;
default:
console.log("Case default");
break;
}
Javascript For statement
• // Array of daily sales
• const dailySales = [120, 250, 330, 400, 150, 220, 310];

• // Calculate and display total sales for each day


• for (let i = 0; i < dailySales.length; i++) {
• console.log(`Day ${i + 1} Sales: $${dailySales[i]}`);
•}
Javascript switchcase
• // Function to categorize sales
• function categorizeSales(sales) {
• switch (true) {
• case sales < 100:
• return "Low";
• case sales >= 100 && sales < 300:
• return "Medium";
• case sales >= 300:
• return "High";
• default:
• return "Unknown";
• }
• }

• // Calculate and categorize total sales


• const totalSales = dailySales.reduce((total, sales) => total + sales, 0);
• const salesCategory = categorizeSales(totalSales);

• console.log(`Total Sales: $${totalSales}`);


• console.log(`Sales Category: ${salesCategory}`);
Call back Function
• const totalSales = dailySales.reduce((total, sales) => total + sales, 0);
• const salesCategory = categorizeSales(totalSales);
Arrays
• Array is a special variable to hold more than one values
• const person =[“Ram”, “Lakshman”,”Sita”];
• To access each element use indexing i.e. person[0]
• Builtin array properties – length
• Builtin array methods – foreach() , pop(), push(), toString(), join(),
shift(), unshift(),concat(), splice(), slice(), reverse(), sort()
• In JavaScript, arrays use numbered indexes
Arrays – Number indexed
• Arrays are special kinds of objects.
• Because of this, it can have variables of different types in the same
Array.
• We can have objects in an Array , functions in an Array and arrays in
an Array
• myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
Arrays – named index
• Array object elements can be stored as name value pair
• const person={person1:”Ram”, person2:”Lakshman”,person3:”Sita”}
• The Map object in JavaScript is a built-in data structure that allows you to store key-value pairs.
• The set method is used to add or update an element in the Map with a specified key and value.
• // Create a new Map
• let myMap = new Map();

• // Add elements using set method


• myMap.set('name', 'Alice');
• myMap.set('age', 30);
• myMap.set('city', 'New York');
• console.log(myMap); // Output: Map(3) {"name" => "Alice", "age" => 30, "city" => "New York"}

• new array() constructor to create an empty array i.e. const person=new array();
• typeof , instanceof operators to know the type of the variable i.e Array
Array methods examples
• let fruits = ['Apple', 'Banana', 'Cherry'];
• let numbers = new Array(1, 2, 3, 4, 5);
• fruits.push('Orange');
• console.log(fruits); // Output: ['Apple', 'Banana', 'Cherry', 'Orange']
• fruits.unshift('Mango');
• console.log(fruits); // Output: ['Mango', 'Apple', 'Banana', 'Cherry']
• let doubled = numbers.map(num => num * 2);
• console.log(doubled); // Output: [2, 4, 6, 8, 10]
• let evenNumbers = numbers.filter(num => num % 2 === 0);
• console.log(evenNumbers); // Output: [2, 4]
Write the codesnippets using
javascript
• Create a numeric indexed array using income values show the output in new html
document
• Get income values of a family members and display the total income using a popup
window
• Update two income values due to yearly hike and show the updated total income in a
paragraph element along with other member details
• Arrange the income values in ascending and decending order
• Create a higher income array by checking the condition >50000
• Create a numeric indexed string valued array using fruit names and display the fruits array
in html page as ordered list
• Write a JavaScript that calculates the squares and cubes of the numbers from 0 to 10 and
outputs html text that displays the resulting values in an html table format.
• Design a volunteer registration form for ABC food bank website using HTML, CSS and
apply validation
Array object with foreach method
• <script>
• const fruits = ["Banana", "Orange", "Apple", "Mango"];

• let text = "<ul>";


• fruits.forEach(myFunction);
• text += "</ul>";

• document.getElementById("demo").innerHTML = text;

• function myFunction(value) {
• text += "<li>" + value + "</li>";
• }
• </script>
Element manipulation in array
• fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
• fruits[fruits.length] = "Lemon";
• fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
• fruits.pop(); //remove an element from fruits
• document.getElementById("demo").innerHTML = fruits instanceof
Array;
• Result : True
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
• Result: Banana * Orange * Apple * Mango
Element manipulation in array
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = fruits.shift();
• Result : Banana
• const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
• Result : 1,2,3,4,5,6
• const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
Result : 3
• fruits.includes("Mango"); // is true
Element manipulations in arrays
• Find returns a value that passes a test condition
• const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
• const temp = [27, 28, 30, 40, 42, 35, 30,50];
• let high = temp.findLast(x => x > 40);
Element manipulations in Arrays
• Returns index that passes the test condition
• const numbers = [4, 9, 16, 25, 29];
let first = numbers.findIndex(myFunction);

function myFunction(value, index, array) {


return value > 18;
}
• Sort method sorts an array alphabetically:
• const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
• fruits.reverse();
Element manipulations in arrays
• Create a new array and sort
• const months = ["Jan", "Feb", "Mar", "Apr"];
const sorted = months.toSorted();
• sort() method will produce incorrect result when sorting numbers.
• Fix this by providing a compare function:
• const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
Document Object Model
• Document Object Model (DOM) is a platform and language-neutral interface that allows
programs and scripts to dynamically access and update the content, structure, and style of a
document
• With the HTML DOM, JavaScript can access and change all the elements of the HTML document
• When a web page is loaded, the browser creates Document Object Model of the page as tree of
objects.

• With the object model javascript gets all the power to create dynamic pages
Document Object Model
• The HTML DOM is a standard for how to get, change, add, or delete
HTML elements. DOM 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
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page
Document Object Model
• Using Javascript HTML DOM methods, actions can be performed on HTML
Elements.
• Using Javascriot HTML DOM properties, values of HTML Elements can be set or
changed.
• The programming interface is the properties and methods of each object.
• Applying getElementById – method, innerHTML – property, an element content can
be modified
Method
• Various Description
methods to access HTML elements
document.getElementById(id) Find an element by element id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(nam Find elements by class name
• Changing the HTML elements
Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element

• Adding and deleting HTML elements


Method Description
document.createElement(element) Create an HTML element
element.removeChild(element) Remove an HTML element
element.appendChild(element) Add an HTML element
element.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
• Adding Event Handlers
Method Description
document.getElementById(id).onclick = Adding event handler code to an onclick event
function(){code}

• Finding HTML objects


Property Description DOM

document.anchors Returns all <a> elements 1


that have a name attribute

document.baseURI Returns the absolute base 3


URI of the document

document.body Returns the <body> 1


element
• Finding HTML objects
Property Description DOM

document.doctype Returns the document's doctype 3


document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the 3
Internet Explorer browser
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the 1
document server
DOM examples – creating div
element
• var y=document.createElement("DIV");
• y.setAttribute("style",
• "width:300px;height:100px;border:red solid");
• y.setAttribute("id","div1");
• document.body.appendChild(y);
DOM examples – creating label
element
• var z=document.createElement("LABEL");
• z.setAttribute("for","in1");
• z.setAttribute("id","l1");
• document.getElementById("div1").appendChild(z)
• document.getElementById("l1").innerHTML="NAME :";
DOM examples – creating input
element
• var x = document.createElement("INPUT");
• x.setAttribute("type", "text");
• x.setAttribute("id","in1");
• x.setAttribute("name","in1");
• x.setAttribute("value", "Dr Meenakshi S P");
• d=document.getElementsByTagName("DIV")[0].appendChild(x);
•}
DOM examples – removing
element
• x=document.getElementById("l1");
• x.remove();

• z=document.getElementById("div1");
• z.remove();

• document.body.remove()
DOM example –removing child
element
• <ul id="myList">
• <li>Coffee</li>
• <li>Tea</li>
• <li>Milk</li>
• </ul>
• const list = document.getElementById("myList");
• list.removeChild(list.firstElementChild);
DOM example –replace child
element
• <ul id="myList">
• <li>Coffee</li>
• <li>Tea</li>
• <li>Milk</li>
• </ul>
• var x = document.createElement("li");
• x.setAttribute("id","l1");
• x.innerHTML="Mylo";
• const list = document.getElementById("myList");
• list.replaceChild(x, list.children[0]);
Dom Example – adding event
handlers
• document.getElementById("b1").onclick=function myFunction() {
• var x = document.createElement("li");
• x.setAttribute("id","l1");
• x.innerHTML="Mylo";

• const list = document.getElementById("myList");


• list.replaceChild(x,list.children[1]);
•}
DOM Example – document
properties
• document.write(document.baseURI);
• document.write(document.documentURI);
• document.write(document.domain);
DOM Examples
• const element = document.getElementsByTagName("p");
• const x = document.forms["frm1"];
let text = "";
for (let i = 0; i < x.length; i++) {
text += x.elements[i].value + "<br>";
}
• Form validation using javascript
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Other Element Selection methods
• querySelector Method
• The querySelector method returns the first element that matches a
specified CSS selector or group of selectors within the document.
• If no matches are found, it returns null.
• document.querySelector(selectors);
querySelector Example
• <!DOCTYPE html>
• <html>
• <head>
• <title>querySelector Example</title>
• </head>
• <body>
• <h1 class="title">Hello, World!</h1>
• <p class="content">This is a paragraph.</p>
• <p class="content">This is another paragraph.</p>


querySelector Example
• <script>
• // Select the first element with the class 'content'
• const firstContent = document.querySelector('.content');
• console.log(firstContent); // Outputs: <p class="content">This is a
paragraph.</p>
• </script>
• </body>
• </html>
Query Selector example – different
CSS Properties
• Tag Selector
• const paragraph = document.querySelector('p');
• console.log(paragraph); // Selects the first <p> element
• Class Selector
• const firstContent = document.querySelector('.content');
• console.log(firstContent); // Selects the first element with the class 'content‘
• Id selector
• const heading = document.querySelector('#heading');
• console.log(heading); // Selects the element with the ID 'heading'
Query Selector example – different CSS
Properties
• Select with element attribute
• const inputRequired = document.querySelector('input[required]');
• console.log(inputRequired); // Selects the first <input> element with the
'required' attribute
• Select with element attribute value
• const specificType = document.querySelector('input[type="email"]');
• console.log(specificType); // Selects the first <input> element with type 'email'
• Select element using pseudo classes
• const firstChild = document.querySelector('ul li:first-child');
• console.log(firstChild); // Selects the first <li> element inside a <ul>
QuerySelectorAll method
• The querySelectorAll method returns a static NodeList of all elements
that match a specified CSS selector or group of selectors within the
document.
• If no matches are found, it returns an empty NodeList.
• Syntax
• document.querySelectorAll(selectors);
QuerySelectorAll method example
• <!DOCTYPE html>
• <html>
• <head>
• <title>querySelectorAll Example</title>
• </head>
• <body>
• <h1 class="title">Hello, World!</h1>
• <p class="content">This is a paragraph.</p>
• <p class="content">This is another paragraph.</p>
QuerySelectorAll method example
• <script>
• // Select all elements with the class 'content'
• const allContent = document.querySelectorAll('.content');
• allContent.forEach((element) => {
• console.log(element);
• // Outputs:
• // <p class="content">This is a paragraph.</p>
• // <p class="content">This is another paragraph.</p>
• });
• </script>
• </body>
• </html>
Event Handling
• Events are actions or occurrences that happen in the browser, such as clicks, key
presses, mouse movements, and more.
• JavaScript can respond to these events by executing specific functions known as event
handlers or event listeners.
• Steps to Handle Events in JavaScript
• Select an Element:
• Use methods like getElementById, querySelector, or querySelectorAll to select the HTML element
you want to attach an event to.
• Add an Event Listener:
• Use the addEventListener method to attach an event listener to the selected element. This
method takes two arguments: the type of event (e.g., 'click') and the function to be executed
when the event occurs.
• Define the Event Handler:
• The event handler function contains the code you want to execute when the event occurs.
Events
• JavaScript can handle a wide variety of events in HTML to create
interactive web
• Mouse Events
• Keyboard Events
• Form Events
• HTML5 Events
• Media Events
• Clipboard Events
• Other Events
Mouse Events
• click: Fires when an element is clicked.
• dblclick: Fires when an element is double-clicked.
• mouseover: Fires when the mouse pointer is moved onto an element.
• mouseout: Fires when the mouse pointer is moved out of an element.
• mousedown: Fires when the mouse button is pressed over an element.
• mouseup: Fires when the mouse button is released over an element.
• mousemove: Fires when the mouse pointer is moved over an element.
• mouseenter: Fires when the mouse pointer is moved onto an element.
• mouseleave: Fires when the mouse pointer leaves an element.
Keyboard Events
• keydown: Fires when a key is pressed down.
• keyup: Fires when a key is released.
• keypress: Fires when a key is pressed down and released.
Form Events

• submit: Fires when a form is submitted.


• reset: Fires when a form is reset.
• focus: Fires when an element gains focus.
• blur: Fires when an element loses focus.
• change: Fires when the value of an element changes.
• input: Fires when the value of an <input>, <textarea>, or <select>
element is changed.
HTML5 Events

• drag: Fires when an element is dragged.


• dragstart: Fires when the user starts dragging an element.
• dragend: Fires when the user has finished dragging an element.
• dragover: Fires when a dragged element is being dragged over a valid
drop target.
• dragenter: Fires when a dragged element enters a valid drop target.
• dragleave: Fires when a dragged element leaves a valid drop target.
• drop: Fires when an element is dropped.
Media Events

• play: Fires when the media is ready to start playing.


• pause: Fires when the media is paused.
• ended: Fires when the media has reached the end.
• volumechange: Fires when the volume changes.
Clipboard Events

• copy: Fires when the content is copied.


• cut: Fires when the content is cut.
• paste: Fires when the content is pasted.
Other Events

• load: Fires when an entire page or an image is fully loaded.


• unload: Fires when the user navigates away from a page.
• resize: Fires when the browser window is resized.
Window resize example
• <!DOCTYPE html>
• <html>
• <head>
• <title>Window Resize Event Example</title>
• </head>
• <body>
• <h1>Resize the Window</h1>
• <p id="dimensions">Current dimensions: </p>

• <script>
• const dimensions = document.getElementById('dimensions');
Window resize example

• // Function to update dimensions text


• function updateDimensions() {
• const width = window.innerWidth;
• const height = window.innerHeight;
• dimensions.textContent = `Current dimensions: ${width}px x ${height}px`;
• }

• // Add event listener for window resize


• window.addEventListener('resize', updateDimensions);
Window resize example

• // Initial call to display dimensions on page load


• updateDimensions();
• </script>
• </body>
• </html>
Event handling example - keyup
• <!DOCTYPE html>
• <html>
• <head>
• <title>Keyup Event Example</title>
• </head>
• <body>
• <h1>Keyup Event Handling</h1>
• <label for="inputField">Type something: </label>
• <input type="text" id="inputField">
• <p id="output"></p>
Event handling example - keyup

• <script>
• // Get the input field and output elements
• const inputField = document.getElementById('inputField');
• const output = document.getElementById('output');

• // Add event listener for keyup event


• inputField.addEventListener('keyup', function(event) {
• // Display the current value of the input field
• output.textContent = `You typed: ${inputField.value}`;
• });
• </script>
• </body>
• </html>
Event handling example – mouse
click
• <!DOCTYPE html>
• <html>
• <head>
• <title>Event Handling Example</title>
• </head>
• <body>
• <h1 id="heading">Click the Button</h1>
• <button id="clickButton">Click Me!</button>

• <script>
• // Select the button element
• const button = document.getElementById('clickButton');
Event handling example
• // Define the event handler function
• function handleClick() {
• const heading = document.getElementById('heading');
• heading.textContent = 'Button Clicked!';
• }

• // Add an event listener to the button


• button.addEventListener('click', handleClick);
• </script>
• </body>
• </html>
Form Control elements
• Text Input Controls
• Checkboxes Controls
• Radio Box Controls
• Select Box Controls
• File Select boxes
• Hidden Controls
• Clickable Buttons
• Submit and Reset Buttons
Text control elements
• Single line text control
• Password text contol
• Multiline text control
• <form >
• First name: <input type = "text" name = "first_name" value="first name"
• maxlength="10" />
• </form>
• maxlength="10": Limits the number of characters that can be entered in
the field to 10.
Text control elements – password,
email
• password: <input type = "password" name = "password" value=""
maxlength="10“ required />
• <label for="email">Email:</label><br> <input type="email"
id="email" name="email" required><br><br>

• </form>
Text control elements - textarea
• <form >
• Description : <br />
• <textarea rows = "10" cols = "50" name = "description">description
here...
• </textarea>
• </form>
• <textarea> Tag: Defines a multi-line text input field.
• rows="10": Sets the number of visible text lines in the text area to 10.
• cols="50": Sets the width of the text area to 50 characters.
Media HTML elements
• To add support for HTML5 video streaming, many new HTML multimedia
elements like < video >, < audio > and < canvas > were introduced.
• They were introduced with additional features like that of Javascript API
to add more interactivity and control over the HTML elements and
handle.
• This makes the HTML5 streaming package more powerful and
ubiquitous than flash players.
• One can make customizations to the video or audio stream, change the
playback appearance, and even apply mathematical rules for
computation.
Video HTML element
• < video controls >

• < source src=”movie.mp4″ type=”video/mp4″ >

• < source src=”movie.ogg” type=”video/ogg” >

• < /video >


Control for Media HTML Elements
• Basic controls get initiated by using the controls attributes within the
video tag.
• Play
• Pause
• Seeking
• Volume
• Fullscreen toggle (for video only)
• Caption/subtitles (for video only when available)
• Track (for video only when available)
Custom media control - Javascript
API
• Custom controls are added via event based or optional attributes with
the support of javascript.
• Complex HTML handlers to initiate a calculated action of play, seek,
etc by combining functions of various methods and arrange them in
logic to form a complex function.
• Play()
• Pause()
Custom video control – javascript
example
• // Adding Video Tag with multiple source
• <video id = "myVideoObject">
• <source src = “movie.mp4">
• </video>
• // Adding the HTML buttons with ID
• <button id = "playButton"> Play </button>
• <button id = "pauseButton"> Pause </button>
Custom video control – javascript
example
• // Adding the JavaScript to identify HTML elements
• var myvideoobject = document.getElementById ("myVideoObject");
• var playBtn = document.getElementById ("playButton");
• var pauseBtn = document.getElementById ("pauseButton");

• playBtn.onclick = function () {
• myvideoobject.currentTime = 10; // Jumps to 10 seconds into the video
• myvideoobject.volume = 0.5; // Sets volume to 50%
• myvideoobject.play (); }
• pauseBtn.onclick = function () { myvideoobject.pause (); }
Media controls
• The basic controls are required for easy navigation across the video
playback
• Custom controls provide homogeneity in styling and features across
the devices.
• Nowadays, all open source and third party HTML5 players provide
attached javascript with their embed code so that the player remains
constant across devices and browsers.
Accessing form control values
• To get the value of an input in JavaScript, you can use the value property.
• This property returns the current value entered by the user in the input
field.
• // HTML
• <input type="text" id="myInput" />
• // JavaScript
• const input = document.getElementById("myInput"); const inputValue =
input.value;
• console.log(inputValue);
Focus, reset method
• To give input focus to a control when it is invalid, focus method is
used
• document.getElementById("myInput").focus();
• The reset() method resets the values of all elements in a form
• document.getElementById("myForm").reset();
Event handlers for onmouseover,
onmouseout
• <img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif"
alt="Smiley" width="32" height="32">
• <script>
• function bigImg(x) {
• x.style.height = "64px";
• x.style.width = "64px";
• }

• function normalImg(x) {
• x.style.height = "32px";
• x.style.width = "32px";
• }
• </script>
Event handlers for onchange
• Call a function when a user changes the selected option of a <select>
element
• <select id="mySelect" onchange="myFunction()">
• <option value="Audi">Audi</option>
• <option value="BMW">BMW</option>
• <option value="Mercedes">Mercedes</option>
• <option value="Volvo">Volvo</option>
• </select>
• <p id="demo"></p>
Event handlers for onchange
• <script>
• function myFunction() {
• var x = document.getElementById("mySelect").value;
• document.getElementById("demo").innerHTML = "You selected: " +
x;
•}
• </script>
External javascript file
• External scripts are practical when the same code is used in many different
web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
• Example
• <script src="myScript.js"></script>
• myScript.js
• function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
Exercise
• Create a html form to get an applicant details like name, email
address, phone number and passport photo. Validate each of field
using the following constraints
• 1. Name entered in uppercase
• 2. Email is in proper format
• 3. Phone number is in valid length
• 4. photosize is less than 500 kB
• Use the events focus, onchage, reset as required.
Built-in-objects
In JavaScript, almost "everything" is an object.
•Booleans can be objects (if defined with the new keyword)
•Numbers can be objects (if defined with the new keyword)
•Strings can be objects (if defined with the new keyword)
•Dates are always objects
•Maths are always objects
•Regular expressions are always objects
•Arrays are always objects
•Functions are always objects
•Objects are always objects
Javascript Primitives
JavaScript defines 5 types of primitive data types:
•string
•number
•boolean
•null
•Undefined
•Primitive values are immutable
•A primitive value is a value that has no
properties or methods.
Javascript Objects
• Objects are variables contain single/many values
• Object values are written as name : value pairs (name and value
separated by a colon)
• let person = "John Doe"; /single value
• let person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
• A JavaScript object is a collection of named values
• It is common practice to declare Objects with const keyward
• The named values, in JavaScript objects, are called properties.
Property Value
firstName John
lastName Doe
Javascript Objects
• Objects written as name value pairs in javascript are similar to
Dictionaries in Python and Hash tables in C
• Objects Methods
• Methods are actions that can be performed on objects.
• Object properties can be both primitive values, other objects, and
functions.
• An object method is an object property containing a function
definition.
• JavaScript objects are containers for named values, called properties
and methods.
Javascript Objects

There are different ways to create new objects:


•Create a single object, using an object literal.
•Create a single object, with the keyword new.
•Define an object constructor, and then create
objects of the constructed type.
•Create an object using Object.create().
• An object literal is a list of name:value pairs (like age:50) inside curly
braces {}.
• The following example creates a new JavaScript object with four
properties:
•const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Javascript Objects
• Creating objects using new keyword
• The following example creates new object then assign four properties
• const person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
• Objects are addressed by reference and not by value
More on Javascript properties
• Properties are the values associated with a JavaScript object.
• A JavaScript object is a collection of unordered properties.
• Properties can usually be changed, added, and deleted, but some are read only.
• Accessing javascript properties
• objectName.property // person.age
• objectName["property"] // person["age"]
• objectName[expression] // x = "age"; person[x]
• Javascript for … in statement loops through the properties of an object
• const person = {
fname:" John",
lname:" Doe",
age: 25
};

for (let x in person) {


txt += person[x];
}
• add new properties to an existing object by simply giving it a value.
• person.nationality = "English";
Javascript properties
• delete person.age; // to delete a property
• Values in object may be another object
• All properties have a name. In addition they also have a value.
More on Javascript Methods
• In JavaScript, the this keyword refers to an object.
• Which object depends on how this is being invoked (used or called).
In a function, this refers to the global object.
In a function, in strict mode, this is undefined.
In an event, this refers to the element that received the event.
Methods like call(), apply(), and bind() can refer this to any object.

• JavaScript methods are actions that can be performed on objects.


• A JavaScript method is a property containing a function definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}
More on Javascript Methods
• Methods are functions stored as object properties.
• const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
• Accessing object methods
• objectName.methodName()
• name = person.fullName();
• If you access the fullName property, without (), it will return the function definition:
More on Javascript Methods
• Adding a method to the object
• person.name = function () {
return this.firstName + " " + this.lastName;
};
• Built-in-methods
• let message=“First string object”;
• Let x=message.toUpperCase();
Storing objects in local storage
• Local storage is a way to store data on the client-side so that it persists even when
the page is refreshed or the browser is closed and reopened.
• Steps for storing
• Convert Object to JSON String: JavaScript objects need to be converted to JSON
strings before storing them in local storage. This is done using the JSON.stringify()
method.
• Store JSON String in Local Storage: Use the localStorage.setItem() method to store
the JSON string in local storage.
• Retrieve JSON String from Local Storage: Use the localStorage.getItem() method to
retrieve the JSON string from local storage.
• Convert JSON String back to Object: Convert the JSON string back to a JavaScript
object using the JSON.parse() method.
Example for local storage of objects
• <script>
• // Object to be stored
• const user = {
• name: "Alice",
• age: 30,
• email: "[email protected]"
• };

• // Convert object to JSON string and store it in local storage


• localStorage.setItem("user", JSON.stringify(user));

• // Retrieve JSON string from local storage and convert it back to object
• const storedUser = JSON.parse(localStorage.getItem("user"));

• console.log(storedUser); // Output: {name: "Alice", age: 30, email: "[email protected]"}


• </script>
Exercise
• Create student object with the properties: name, register, number,
subject marks, findnamelength method, average marks method and
findsubject method. Create a html form to get student details for 10
students and store it in local storage. Create another page to display
the student details one by one.
Javascript Built-in-Objects
• JavaScript also has four built-in objects: Array, Date, Math, and
String.
• Each object has special-purpose properties and methods associated
with it.
• Array object
• const person =[“Ram”, “Lakshman”,”Sita”];
• Builtin array methods – foreach() , pop(), push(), toString(), join(),
shift(), unshift(),concat(), splice(), slice(), reverse(), sort()
• Date object
• Var date_obj = new Date(January 1 1996)
Javascript Built-in-Objects
• Date Methods
• getHours() - Returns the hour
• getMinutes() - Returns the minutes
• getSeconds() - Returns the seconds
• getYear() - Returns the year ("96" is 1996)
• Math Object
• The Math object is static, so no need to create a new Math object in order to use it.
• To access the properties and method of the Math object, specify the Math object,
along with the method or property
• var pi=Math.PI;
• var pieRound=Math.round(pi);
Javascript Built-in-Objects
• Math Properties
E Euler's constant
LN2 The natural logarithm of 2
LN10 The natural logarithm of 10
LOG2E The base 2 logarithm of e
LOG10E The base 10 logarithm of e

• Math Methods
ceil Returns the least integer greater than or equal to a number

cos Returns the cosine of a number

exp Returns e (Euler's constant) to the power of a number

floor Returns the greatest integer less than or equal to its argument

log Returns the natural logarithm (base e) of a number


Javascript Built-in-Objects
• String Object
• New string objects are created implicitly using a variable assignment.
• var mystring=“newstring”
• Properties
• Length
• Methods
big Sets text to big

blink Sets text to blinking

bold Sets text to bold

charAt Returns the character at a specified position

fixed Sets text in fixed-pitch font


Javascript Regular Expressions
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to
describe what you are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text
replace operations.
• Syntax /pattern/modifier
• /w3schools/i is a regular expression.
• w3schools is a pattern (to be used in a search).
• i is a modifier (modifies the search to be case-insensitive).
Regular Expressions
• In JavaScript, regular expressions are often used with the
two string methods: search() and replace().
• The search() method uses an expression to search for a match,
and returns the position of the match.
• The replace() method returns a modified string where the
pattern is replaced. Modifier Description
let text="Hello world";
i Perform case-insensitive
let x=text.search("world"); matching

let x=text.search(/world/i) -> using regular expression g Perform a global match (find all
let y=text.replace(/world/i, "Globe"); matches rather than stopping
after the first match)
let text = "\nIs th\nis it?"; m Perform multiline matching
let result = text.match(/^is/m);
Regular Expressions
• Brackets are used to find a range of characters:
Expression Description
[abc] Find any of the characters between the brackets
[0-9] Find any of the digits between the brackets
(x|y) Find any of the alternatives separated with |

• Metacharacters are characters with a special meaning:


Metacharacter Description
\d Find a digit
\s Find a whitespace character
\b Find a match at the beginning of a word like this: \bWORD,
or at the end of a word like this: WORD\b
\uxxxx Find the Unicode character specified by the hexadecimal
number xxxx
Regular Expressions
• Quantifiers define quantities:
Quantifier Description
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
• The test() method is a regular expression method
• It searches a string for a pattern, and returns true or false depending on the
result
• const pattern=/e/
• z=pattern.test("There is a trigger");
Regular Expressions
• The exec() method is a RegExp expression method.
• It searches a string for a specified pattern, and returns the found text as an object.
• If no match is found, it returns an empty (null) object.
• const pattern=/trig/
• z=pattern.exec("There is a trigger");
.

Javascript Exceptions
• When an error occurs, JavaScript will normally stop and generate an error message.
• The technical term for this is: JavaScript will throw an exception (throw an error).
• JavaScript will actually create an Error object with two properties: name and message.
• Using throw statement
• The throw statement allows you to create a custom error.
• Technically you can throw an exception (throw an error).
• The exception can be a JavaScript String, a Number, a Boolean or an Object:
• If you use throw together with try and catch, you can control program flow and
generate custom error messages
• Ex : throw “Error text”; throw 500;
Javascript Exceptions
• Example
• <p id="p1" >Some Text</p>
<script>
alert("A text change");
const message=document.getElementById("p1");
try{
x=document.getElementById("p1").innerHTML;
if(x=="")
throw "Text Empty";
else
throw x;
}
catch(err)
{
message.innerHTML="The error message: " + err;
}
</script>
Javascript Exceptions
• The finally statement lets you execute code, after try and catch, regardless of the result:
• try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code to be executed regardless of the try / catch result
}
• Javascript error object
• JavaScript has a built in error object that provides error information
when an error occurs.
• The error object provides two useful properties: name and message.
Javascript
• Error object properties
Exceptions
Property Description
name Sets or returns an error name
message Sets or returns an error message (a string)

• Error Name values


Error Name Description
EvalError An error has occurred in the eval() function
RangeError A number "out of range" has occurred
ReferenceError An illegal reference has occurred
SyntaxError A syntax error has occurred
TypeError A type error has occurred
URIError An error in encodeURI() has occurred
Javascript Exceptions
• Reference Error Example
• <p id="p1" >Some Text</p>
<script>
alert("A text change");
const x=5;
const message=document.getElementById("p1");
try{
x=y+1;
}
catch(err)
{
message.innerHTML="The error message: " + err.name + "<br> " + err.message;
}
</script>
Javascript Event Handling
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on these
events.
• Examples
• An HTML web page has finished loading
• An HTML input field was changed
• An HTML button was clicked
• JavaScript lets you execute code when events are detected.
• HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
Javascript Event Handling
• Syntax : for javascript event handler
• <element attribute=“javascript code”>
• <button onclick=“this.innerHTML = Date()">The time is?</button>
//event handling using javascript code
• <button onclick="displayDate()">The time is?</button> // event
handling using javascript fuctions
Event Description

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


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
• <img onmouseover="bigImg(this)" onmouseout="normalImg(this)" border="0" src="smiley.gif" alt="Smiley" width="32"
height="32">
• <script>
• function bigImg(x) {
• x.style.height = "64px";
• x.style.width = "64px";
• }

• function normalImg(x) {
• x.style.height = "32px";
• x.style.width = "32px";
• }
• </script>
Data Validation using javascripts
• Data validation is the process of ensuring that user input is clean, correct, and useful.
• 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.
Javascript form validations
• Form validation
• function validateForm()
• {
• let x=document.forms["myform"]["name"].value;
• if(x=="")
• {
• alert("Name field is empty");
• return false;
• }
• }
• </script>

• <form name="myform" action="/action_page.php" onsubmit="return validateForm()" method="post" >


• <label for="in1">Name</label>
• <input type="text" id="in1" name="name" >
• <input type="submit" value="Submit">
• </form>
Javascript automatic 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
• <input type="text" name="fname" required>
HTML constraint validations
• 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
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

Selector Description
:disabled Selects input elements with the "disabled" attribute specified
:invalid Selects input elements with invalid values
:optional Selects input elements with no "required" attribute specified
HTML constraint validations
• Input attribute constraint validation
• Example:<input type="date" id="datemin" name="datemin" min="2000-01-
02"><br><br>
• Pseudo selector constraint validation
• Example : a.highlight:hover {
color: #ff0000;
}
• DOM method constraint validation
• <script> document.getElementById('foo').validity.typeMismatch; //false
document.getElementById('bar').validity.typeMismatch; //true
</script>
JQuery
• jQuery is a fast, small, and feature-rich JavaScript library.
• It makes things like HTML document traversal and manipulation, event handling, animation,
and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.
• jQuery greatly simplifies JavaScript programming.
• Jquery will be used when the document is ready
• all jQuery methods in our examples, are inside a document ready event:
• $(document).ready(function(){

// jQuery methods go here...

});
• This is to prevent any jQuery code from running before the document is finished loading (is
ready).
Jquery - Examples
• The following code hides the paragraph element
• Jquery used to select paragraph element and for the click event , calls
the hide function when the document is ready.
• $(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
Jquery selectors for html elements
• The jQuery element selector selects elements based on the element name.
• You can select all <p> elements on a page like this:
• $("p")
• The jQuery #id selector uses the id attribute of an HTML tag to find the
specific element.
• An id should be unique within a page, so you should use the #id selector
when you want to find a single, unique element.
• To find an element with a specific id, write a hash character, followed by the
id of the HTML element:
• $("#test")
Jquery selectors for html elements
• The jQuery .class selector finds elements with a specific class.
• To find elements with a specific class, write a period character,
followed by the name of the class:
• $(".test") Syntax Description
$("*") Selects all elements
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
jQuery Event Methods

• jQuery is tailor-made to respond to events in an HTML page.


• What are Events?
• All the different visitors' actions that a web page can respond to are
called events.
• An event represents the precise moment when something happens.
• Examples:
• moving a mouse over an element
• selecting a radio button
• clicking on an element
Common DOM events
Mouse Events Keyboard Events Form Events Document/Window Events

click keypress submit load


dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload


jQuery Syntax For Event Methods
• In jQuery, most DOM events have an equivalent jQuery method.

• To assign a click event to all paragraphs on a page, you can do this:

• $("p").click();
• The next step is to define what should happen when the event fires. You
must pass a function to the event:

• $("p").click(function(){
• // action goes here!!
• });
jQuery Syntax For Event Methods
• mouseup()
• The mouseup() method attaches an event handler function to an
HTML element.
• The function is executed, when the left, middle or right mouse button
is released, while the mouse is over the HTML element:
• $("#p1").mouseup(function(){
alert("Mouse up over p1!");
});
jQuery Syntax For Event Methods
• focus()

• The focus() method attaches an event handler function to an HTML form field.

• The function is executed when the form field gets focus:

• Example
• $("input").focus(function(){
• $(this).css("background-color", "#cccccc");
• });
jQuery Animations - The animate() Method

• The jQuery animate() method is used to create custom animations.


• Syntax:
• $(selector).animate({params},speed,callback);
• The required params parameter defines the CSS properties to be
animated.
• The optional speed parameter specifies the duration of the effect. It can
take the following values: "slow", "fast", or milliseconds.
• The optional callback parameter is a function to be executed after the
animation completes.
• $("button").click(function(){
$("div").animate({left: '250px'});
});
Including jquery library from content delivery
network server/ downloading from jQuery.com
• <script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js">
• </script>
• Downloading jQuery
• There are two versions of jQuery available for downloading:
• Production version - this is for your live website because it has been
minified and compressed
• Development version - this is for testing and development (uncompressed
and readable code)
• Both versions can be downloaded from jQuery.com.

You might also like