WINSEM2024-25 BCSE203E ELA VL2024250504295 2025-02-27 Reference-Material-I
WINSEM2024-25 BCSE203E ELA VL2024250504295 2025-02-27 Reference-Material-I
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];
• 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"];
• 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);
• 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
• 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";
•
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
• <script>
• const dimensions = document.getElementById('dimensions');
Window resize example
• <script>
• // Get the input field and output elements
• const inputField = document.getElementById('inputField');
• const output = document.getElementById('output');
• <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!';
• }
• </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 >
• 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
• // Retrieve JSON string from local storage and convert it back to object
• const storedUser = JSON.parse(localStorage.getItem("user"));
• Math Methods
ceil Returns the least integer greater than or equal to a number
floor Returns the greatest integer less than or equal to its argument
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 |
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)
onmouseout The user moves the mouse away from an HTML element
• 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>
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(){
});
• 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
• $("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.
• Example
• $("input").focus(function(){
• $(this).css("background-color", "#cccccc");
• });
jQuery Animations - The animate() Method