WEB Module 3
WEB Module 3
TECHNOLOGIES
Module 3
Module 3
Event Handling and Document Object model in
JavaScript, Handling strings and working with
window object
JAVA SCRIPT EVENTS AND EVENT
LISTENERS
Introduction
4
onclick Event Type
• This is the most frequently used event type which occurs when a
user clicks the left button of his mouse. You can put your validation,
warning etc., against this event type.
• One attribute can appear in several different tags:
e.g. onClick can be in <a> and <input>
• HTML element get focus:
1. When user puts mouse cursor over it and presses the left button
2. When user tabs to the element
3. By executing the focus method
4. Element get blurred when another element gets focus
5
• Event handlers can be specified two ways
1. Assigning the event handler script
to an event tag attribute
onClick = "alert('Mouse click!');"
onClick = "myHandler();
2. Assigning them to properties of JavaScript object
associated with HTML elements.
• The load event: the completion of loading of a document by
browser
• The onload attribute of <body> used to specify event handler
• The unload event: used to clean up things before a document
is unloaded.
6
Example:
<!DOCTYPE html>
<html><head>
<script type="text/javascript"></script></head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()"
value="Say Hello" />
</form>
</body></html>
7
onSubmit Event Type
8
<!DOCTYPE html> Example:
<html><head>
<script type="text/javascript">
</script>
</head><body>
<form method="POST" action="target.html" onsubmit="return validate()">
<input type="submit" value="Submit" />
</form>
</body>
</html>
9
<html>
validation
<head></head>
<body> <center>
<h1 style="color: green;">
Validation program
</h1>
<h3>
Validate Input Fields in HTML Form
</h3> <form action="#" method="post">
<label for="fname">First Name:</label>
<input type="text" name="fname" id="fname"
placeholder="Enter your first name" required minlength="2">
<br><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password"
placeholder="Enter a secure password" required
minlength="8">
<br><br>
<input type="submit" value="Submit">
</form> </center></body>
Event List
1
Focus & Event Example:
[fig.1 Before Click On That Button]
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Hello How Are You...?</h1>
<form>
Click This Button<br/>
<input type="button" value="Click Me!" onclick="myFun()"/><br/>
<input type="text" id="username" onfocus="this.blur()"/>
<br/>
</form> [fig.2 After Click On That Button]
<script type="text/javascript">
function myFun()
{
document.getElementById("username").value="shree";
}
</script>
</body>
</html>
addEventListener
• The Event Target method addEventListener() sets up a
function that will be called whenever the specified
event is delivered to the target.
• Common targets are Element, Document, and Window, but the
target may be any object that supports events (such as XML Http
Request).
1
Syntax
target.addEventListener(type, listener[, options]);
target.addEventListener(type, listener[, useCapture]);
target.addEventListener(type, listener[, useCapture,
wantsUntrusted ]);
document.getElementById("myBtn").addEventListener("click",
displayDate);
1
removeEventListener
• The EventTarget.removeEventListener() method removes
from the EventTarget an event listener previously
registered with EventTarget.addEventListener().
1
Syntax
target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[, useCapture]);
1
Other Example Of Events
<!DOCTYPE html>
<html>
<head><title>Display Page</title></head>
<body>
<hr color="orange" />
<center><h1 id="htag">Welcome To ADIT</h1></center>
<hr color="blue" />
<center><button type="button" onclick="Change()">Change</button>
<button type="button" onclick="Hide()">Hide</button>
<button type="button" onclick="Display()">Display</button>
<button type="button" onclick="ChangeColor()">Color Change</button></center>
<hr color="green" />
<script type="text/javascript"> function Change()
{ document.getElementById("htag").innerHTML="Welcome ABC"; } function
Display()
{ document.getElementById("htag").style.display="block"; } function Hide()
{ document.getElementById("htag").style.display="none"; } function
ChangeColor()
{ document.getElementById("htag").style.color="blue"; }
</script>
</body>
</html>
Output
1
Event Listeners
• Event listeners are the foundation of event handling
in the DOM.
• An event listener is a function that waits for a
specific event to occur on an HTML element and
executes a set of instructions when the event is
triggered.
example:
const button = document.querySelector('button');
button.addEventListener('click', () => {
alert('Button clicked!');
});
• we first select a button element using the querySelector()
method.
• We then attach an event listener to the button using the
addEventListener() method.
• The event we're listening for is 'click', and the function we
want to execute when the event occurs is an anonymous
function that displays an alert message.
Using DOM and Events:
// Keyboard Event
document.addEventListener("keydown", (e) => {
console.log(`Key pressed: ${e.key}`);
});
we're listening for a click event on a button element, and displaying an alert message
when the button is clicked.
2. Keyboard Events
we're listening for a keypress event on the entire document. When a key is pressed, the
event object is passed to the callback function, and we display a message in the console
that shows which key was pressed.
3. Form Events
Form events are used to handle interactions with HTML form elements.
we're listening for a submit event on a form element. When the form is submitted, we prevent
the default behavior (which is to reload the page), and display the value of the input field in the
console.
4 Window Events
Window events are used to handle interactions with the browser window.
window.addEventListener('resize', () => {
x${window.innerHeight}`);
});
we're listening for a resize event on the window object. When the window is resized, we
display the new width and height of the window in the console.
5. Touch Events
Touch events are used to handle interactions with touchscreens on mobile devices. Here's an
example of how to handle a touchstart event:
we're listening for a touchstart event on a box element. When the user touches the box, we
display the coordinates of the touch in the console.
Removing Event Listeners
To remove an event listener, use the removeEventListener() method. This is useful when
you no longer need the event handler to execute, such as when components are removed
from the DOM.
Example:
button.addEventListener('click', handleClick);
Output:
example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling</title>
<style>
body { text-align: center; font-family: Arial, sans-serif; }
</style>
</head>
<body>
<h2>Click the Button</h2>
<button id="btn">Click Me</button>
<p id="msg"></p>
<script>
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("msg").textContent = "Button Clicked!";
});
</script>
</body>
Output
Add text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>DOM Methods Example</title>
<style> body { text-align: center; font-family: Arial, sans-
serif; }
</style></head><body>
<h2>DOM Methods Example</h2>
<button id="btn">Click Me</button>
<p id="msg"></p>
<button id="addText">Add Text</button>
<div id="container"></div>
<body>
<h2>DOM Methods Example</h2>
<button id="btn">Click Me</button>
<p id="msg"></p>
<button id="addText">Add Text</button>
<div id="container"></div><script>
// Changing text content on button click
document.getElementById("btn").addEventListener("click", function() {
document.getElementById("msg").textContent = "Button Clicked!";
});
<p>Click the button to open a new window, and set focus to it.</p>
<script>
function myFunction() {
const myWindow = window.open("", "", "width=200,height=100");
myWindow.focus();
}
</script>
</body>
setInterval()
• This method calls on a function with a specific
interval.
• setInterval(function, milliseconds, param1,.....)
Example
setInterval(displayHi, 1000);
function displayHi() {
document.getElementById("demo").innerHTML +=
"Hello world";
}
Example
<body> <body>
</body> </body>
• The setInterval() method calls a function at specified
intervals (in milliseconds).
• The setInterval() method continues calling the function
until clearInterval() is called, or the window is closed.
• 1 second = 1000 milliseconds.
Interval time example
<body>
<p id="demo"></p>
<script>
setInterval(myTimer, 1000);
function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
</script>
</body>
clearInterval()
• The clearInterval() method that clears the time set by the setInterval()
method.
• clearInterval(functon_name);
EX
• const mynewInterval = setInterval(mynewTimer, 1000);
function mynewTimer() {
const date = new Date();
document.getElementById("demo").innerHTML =
date.toLocaleTimeString();
}
function mynewStopFunction() {
clearInterval(mynewInterval);
}
Interval and clear interval
<body>
<h1>The Window Object</h1>
<h2>The setInterval() and clearInterval() Methods</h2>
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<script>
const myInterval = setInterval(myTimer, 1000);
function myTimer() {
const date = new Date();
document.getElementById("demo").innerHTML = date.toLocaleTimeString();
}
function myStopFunction() {
clearInterval(myInterval);
}
</script>
</body>
Interval and clear interval(color)
<body>
<h1>The Window Object</h1>
<h2>The setInterval() and clearInterval() Methods</h2>
<p>In this example, the setInterval() method executes the setColor() function once every 500
milliseconds
to toggle between two background colors.</p>
<button onclick="stopColor()">Stop Toggling</button>
<script>
myInterval = setInterval(setColor, 1000);
function setColor() {
let x = document.body;
x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}
function stopColor() {
clearInterval(myInterval);
}
</script>
</body>
<body>
<p id="demo1"></p>
<script>
setInterval(function() {myFunc("param1", "param2")}, 2000);
</body>
Output
setTimeout()
• The clearTimeout() method that clears the time set by the setTimeout()
method.
• clearTimeout(function_name);
• const mynewTimeout = setTimeout(mynewGreeting, 3000);
function mynewGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday to
You !!"
}
function mynewStopFunction() {
clearTimeout(mynewTimeout);
}
• We have to clear the timer within the setTimeout() method.
example
<body><h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<button onclick="startCount()">Start count!</button>
<input type="text" id="demo">
<button onclick="stopCount()">Stop count!</button>
<p>Click on "Start count!" to start the timer. The input field will count forever, starting at 0.</p>
<p>Click on "Stop count!" to stop counting. Click on "Start count!" to start the timer again.</p>
<script>
let counter = 0;
let timeout;
let timer_on = 0;
function timedCount() {
document.getElementById("demo").value = counter;
counter++;
timeout = setTimeout(timedCount, 1000);
}
function startCount() {
if (!timer_on) {
timer_on = 1;
timedCount();
}}
function stopCount() {
clearTimeout(timeout);
timer_on = 0;
}
</script>
output
close()
The close() method closes the window
window.close()
function closenewWin() {
mynewWindow.close();
}
example1
<body>
<h1>The Window Object</h1>
<h2>The open() and close() Methods</h2>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
let myWindow;
function openWin() {
myWindow = window.open("", "", "width=200,height=100");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
Output
Example 2
<body>
<h1>The Window Object</h1>
<h2>The open() and close() Method</h2>
<button onclick="openWin()">Open w3schools.com in a new window</button>
<button onclick="closeWin()">Close the new window</button>
<script>
let myWindow;
function openWin() {
myWindow = window.open("https://www.w3schools.com", "_blank", "width=500,
height=500");
}
function closeWin() {
myWindow.close();
}
</script>
</body>
Output
• Synatx: confirm(message)
• confirm("Click Me!");
• function mynewFunction() {
confirm("Press a button!");
}
example
<body><h1>The Window Object</h1>
<h2>The confirm() Method</h2>
<p>Click the button to see line-breaks in a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text = "Press a button!\nEither OK or Cancel.";
if (confirm(text) == true) {
text = "You pressed OK!“ THANK YOU;
} else {
text = "You canceled!";
}
document.getElementById("demo").innerHTML = text;
}
output
scrollBy() method
• The scrollBy() method scrolls the document
by the specified number of pixels.
• Syntax: window.scrollBy(x, y)
<!DOCTYPE html>
<html><body><h1>The Window Object</h1>
<h2>The scrollBy() Method</h2>
<p>Click to scroll the document.</p>
<button onclick="scrollWin()" style="position:fixed">Scroll 100px vertically!</button>
<br><br>
<h3>Some line breaks to enable scrolling:</h3>
<br><br><br><p>When I find myself in times of trouble</p>
<br><br><br>
<p>Mother Mary comes to me</p>
<br><br><br>
<p>Speaking words of wisdom, let it be</p>
<br><br><br>
<p>And in my hour of darkness she is standing right in front of me</p>
<br><br><br>
<p>Speaking words of wisdom, let it be</p>
<br><br><br>
<p>ROCK AND ROLL</p>
<br><br><br>
<p>SCROLL SCROLL SCROLL</p>
<br><br><br>
<p>ROCK AND ROLL</p>
<br><br><br>
<p>SCROLL SCROLL SCROLL</p>
<br><br>
<br><p>ROCK AND ROLL</p>
<br><script>
function scrollWin() {
window.scrollBy(0, 100);
}
</script></body></html>
JavaScript String handling
• Strings are for storing text & digit values
• Strings are written with quotes
• JavaScript strings are the sequence of
characters.
• In JavaScript, strings are automatically
converted to string objects when using string
methods on them.
• This process is called auto-boxing.
The following are methods that we can call on strings
• slice()
• substring()
• substr() .
• replace()
• replaceAll() .
• toUpperCase()
• toLowerCase()
• trim() .
• trimStart()
• trimEnd()
• padStart()
• padEnd()
• charAt()
• charCodeAt()
• split()
Extracting String Parts
There are 3 methods for extracting a part of a
string:
• slice(start, end)
• substring(start, end)
• substr(start, length)
slice()
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
Output
• Banana
• Banana, Kiwi
• Banana
• Banana, Kiwi
• Kiwi
Examples
//define the string variable
let text = "Java, Python, C";
let A=str.substring(6,13);
let B=str.substring(7);
let C=str.substring(-4);
let D=str.substring(-20);
console.log(A);
console.log(B);
console.log(C);
console.log(D);
• Banana
• Banana, Kiwi
• Kiwi
• Apple, Banana, Kiwi
substr()
let A=str.substring(7,20);
let B=str.substring(-9);
let C=str.substring(1);
let D=str.substring(-7);
console.log(A);
console.log(B);
console.log(C);
console.log(D);
• C, C++, JAVA
• C++, JAVA
• ython, C, C++, JAVA
• +, JAVA
replace()
• It replaces a part of the given string with
another string or a regular expression. The
original string will remain unchanged.
• The replace() method replaces a specified
value with another value in a string:
• The replace() method returns a new string.
• The replace() method replaces only the
first match
let string = 'lang';
console.log(newstring);
console.log(newstring1);
console.log(newstring2);
• Web
• Java
• python
Example
output
• java is a high level programming language
replaceAll()
Output
• Mind, Space, Space, Soul
Example 2
Output
apple,vehical,lang,college
Example 3
Output
manglore,Ajiet,Ajiet,web
toUpperCase()
Output
• COLLEGE NAME
• AJIET MANGLORE
toLowerCase()
• It converts all the characters present in the so
lowercase and returns a new string with all
the characters in lowercase.
Example 1
Output
• college name
• aj institute of engineering and technology
• mangalore
concat()
• It combines the text of two strings and
returns a new combined or joined string.
• To concatenate two strings, we use
the concat() method on one object of string
and send another object of string as a
parameter.
• This method accepts one argument.
• The variable contains text in double quotes
or single quotes.
Example 1
Output:
WEB-TECHNOLOGY
Example 2
• Output: 4 14
trimStart()
• It removes whitespace from the beginning of
a string.
• The value of the string is not modified in any
manner, including any whitespace present
after the string.
Example 1
Example 2
Output :
trimEnd()
• removes white space from the end of a string.
• The value of the string is not modified in any
manner, including any white-space present
before the string.
Example
Output:
WEB TECH
WEB TECH
padStart()
• padStart() pad a string with another string
until it reaches the given length. The padding
is applied from the left end of the string.
Output : 119
97
Example 2
split()
• It splits the string into an array of sub-strings. This
method returns an array.
• This method accepts a single parameter character on
which you want to split the string.
Example 1