0% found this document useful (0 votes)
10 views32 pages

JavaScript Basics: Functions and DOM

Module 5 introduces JavaScript, covering its history, functions, the Document Object Model (DOM), and forms. It explains how JavaScript enhances web pages by enabling dynamic content updates and user input processing, while also detailing the syntax for buttons, functions, and variables. Additionally, it discusses client-side versus server-side form processing, emphasizing the advantages and use cases for each approach.

Uploaded by

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

JavaScript Basics: Functions and DOM

Module 5 introduces JavaScript, covering its history, functions, the Document Object Model (DOM), and forms. It explains how JavaScript enhances web pages by enabling dynamic content updates and user input processing, while also detailing the syntax for buttons, functions, and variables. Additionally, it discusses client-side versus server-side form processing, emphasizing the advantages and use cases for each approach.

Uploaded by

latha yadav
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Module-5

Introduction to JavaScript: Functions, DOM, Forms, and Event


Handlers
5.1. History of JavaScript
 So he designed the JavaScript programming language, which adds dynamic
functionality to web pages when used in conjunction with HTML.
 For example, JavaScript provides the ability to update a web page’s content when an
event occurs, such as when a user clicks a button. It also provides the ability to
retrieve a user’s input and process that input. Other browser manufacturers support
their own versions of JavaScript. For their Internet Explorer and Edge browsers,
Microsoft uses JScript.
 For their Chrome browser, Google uses the V8 JavaScript Engine.
 Fortunately, all the browser manufacturers attempt to follow the ECMA Script
standard, so for most tasks, programmers can write one version of their code and it
works for all the different browsers.
 European Computer Manufacturers Association (ECMA).

5.2. Hello World Web Page

 For the book’s web pages that use JavaScript, as in the Hello web page shown in
Figure 8.1, click the web page’s button, and be amazed as the “To see the …” text
gets replaced by the large “Hello, world!” text.
 in FIGURE 8.2. You can see that there’s not much JavaScript—it’s just the code in
the script container and the code that follows the onclick attribute. The rest of the web
page is HTML code.

5.3. Buttons

 There are different types of buttons, we have one type of button, and here’s its syntax:

<input type="button" value="button-label" onclick="click-event-handler">

 the input tag implements elements that handle user input. You might not think of a
button as user input, but it is—the user chooses to do something by clicking a button.

 input element’s most common attributes—type, value, and onclick.

 The input element is used for different types of user input, and its type attribute
specifies which type of user input and type of control to be implemented.

 where a control is a user input entity such as a button, text control, or checkbox.

 In the Hello web page source code, note that the type attribute gets the value button,
which tells the browser to display a button.
 If you don’t provide a type attribute, the browser will display a text control, because
that’s the default type of control for the input element

 text control is a box that a user can enter text into, and this is what a (filled-in) text
control (with a prompt at its left) looks like:

 The input element’s value attribute specifies the button’s label. If you don’t provide a
value attribute, the button will have no label.

 The input element’s onclick attribute specifies the JavaScript instructions that the
JavaScript engine executes when the user clicks the button.

 Clicking the button is considered to be an event, so the onclick attribute’s JavaScript


code is known as an event handler.

 Besides onclick, there are other attributes that call event handlers, like onfocus and
onload, but they aren’t used much for buttons.

5.4. Functions

 Here’s the syntax for calling a function:

function-name(zero-or-more-arguments-separated-by commas);

 Hello web page button has an onclick attribute with a value of displayHello();. That’s
a JavaScript function call

 Note the parentheses are empty because there’s no need to pass any argument values
to the displayHello function.

 If there were arguments, they would need to be separated by commas.

 Here’s the syntax for a function definition:

function function-name(zero-or-more-parameters-separated-bycommas)
{
statement-1;
statement-2;

last-statement;
}
 Normally, function definitions should be placed

(1) in a script container in the web page’s head container or

(2) in an external JavaScript file.

 Go back to the Hello web page code in Figure 8.2 and verify that the displayHello
function definition is in a script container.

 Three lines in the function’s body. Each line is a JavaScript statement, where a
statement performs a task.

 Semicolons are required at the end of a JavaScript statement only if the JavaScript
statement is followed by another JavaScript statement, so it would have been legal to
omit the semicolon after the last statement.

 However, coding conventions dictate that you terminate every statement with a
semicolon, even the last one. Why?

 Suppose there’s no semicolon at the end of the last statement and someone later adds
a new statement after the last statement. If they forget to insert a semicolon between
the two statements, that creates a bug.

 Another reason to insert a semicolon after the last statement is that if you don’t do it,
the JavaScript engine does it for you behind the scenes, and that slows things down
slightly.

5.6. Variables
 Here’s the function’s first statement:
var msg;
 The msg variable will hold a string that forms a message.
 Before you use a variable in JavaScript code, you should use var to declare the
variable in a declaration [Link]
var name;
var careerGoals;

 Words that are part of the JavaScript language are known as keywords. The word var
is a keyword. On the other hand, name and careerGoals are not keywords because
they are specific to a particular web page’s code and not to the JavaScript language.

 Many programmers use the terms “keywords” and “reserved words” interchangeably,
but there is a slight difference, as not all keywords are reserved words.

 In most programming languages, when you declare a variable, you specify the type of
values that the variable will be allowed to hold—numbers, strings, and so on.

 However, with JavaScript, you do not specify the variable’s type as part of the
declaration. The variable’s type is determined dynamically by the type of the value
that’s assigned into the variable. For example:

name = "Mia Hamm";


careerGoals = 158;
 What type of value is "Mia Hamm"? A string, since a string consists of zero or more
characters surrounded by a pair of double quotes (") or a pair of single quotes (‘).

 What type of value is 158? A number, since a number consists of digits with an
optional decimal point.

 JavaScript is known as a loosely typed language, or a dynamically typed language,


which means that you do not declare a variable’s data type explicitly, and you can
assign different types of values into a variable at different times during the execution
of a program.

5.7. Identifiers

 An identifier is the technical term for a program component’s name—the name of a


function, the name of a variable,
 In the Hello web page, displayHello was the identifier for the function name, and msg
was the identifier for a variable.

 In naming your variables and functions, the JavaScript engine requires that you follow
certain rules.

1. Identifiers must consist entirely of letters, digits, dollar signs($), and/or underscore (_)
characters.
2. The first character must not be a digit.
3. letters should be lowercase / uppercase That’s referred to as camel case,

ex: firstName, message, daysInMonth.

5.8. Assignment Statements and Objects

 When the user clicks the button. To understand how that works, we need to talk about
assignment statements and objects.

 Once again, here’s the Hello web page’s displayHello function:


 In the function’s body, the first statement is a variable declaration for the msg
variable.

 After you declare a variable, you’ll want to use it, and the first step in using a variable
is to put a value inside it. An assignment statement puts/assigns a value into a
variable.

 The function body’s second and third statements are assignment statements. The
assignment operator (=) assigns the value at the right into a variable at the left.

 So in the first assignment statement, the [Link]("message") thing


gets assigned into the msg variable.

 In the second assignment statement, the "<h1>Hello, world!</h1>" thing gets


assigned into the [Link] variable.

 An object is a software entity, object is associated with the entire web page, and that
object’s name is document.

 Each object has a set of related properties, plus a set of behaviors. A property is an
attribute of an object. A behavior is a task that the object can perform.

 The document object contains properties like the web page’s type. Most web pages
these days have a value of HTML5 for the document object’s type property.

<!DOCTYPE html>

 So to access the current web page’s document type, use document for the object
name, . for dot, and doctype for the property. Here’s the JavaScript code:
[Link]

 In JavaScript (and other programming languages), an object’s behaviors are


referred to as methods.
 To retrieve an element, the document object uses its getElemementById method.
To call an object’s method, you specify the object name, a dot, the method name,
and then parentheses around any arguments you want to pass to the method

[Link]("message")

5.9. Document Object Model

 The Document Object Model, which is normally referred to as the DOM, models all
of the parts of a web page document as nodes in a node tree.

 A node tree is similar to a directory tree, it shows web page elements that include
other elements (and text and attributes).

 Each node represents either

(1) an element,

(2) a text item that appears between an element’s start and end tags,

(3) an attribute within one of the elements.

 The figure’s code is a stripped-down version of the Hello web page code shown
earlier.

 The node tree shows blue nodes for each element in the web page code (e.g., head and
title).

 It shows yellow nodes for each text item that appears between an element’s start and
end tags (e.g., “Hello”).

 And it shows green nodes for each attribute in the web page document’s elements
(e.g., h3’s id attribute).
 The DOM provides different ways to access the nodes in the node tree. Here are three
common techniques:

1. You can retrieve the node tree’s root by using document in your code and then use the
root object as a starting point in traversing down the tree.

2. You can retrieve the node that the user just interacted with (e.g. a button that was
clicked) and use that node object as a starting point in traversing up or down the tree.

3. You can retrieve a particular element node by calling the document object’s
getElementById method with the element’s id value as an argument.

In the Hello web page, we used the third technique, calling getElementById

5.10. Forms and How They’re Processed: Client-Side Versus Server-Side

 A form is a mechanism for grouping input controls (e.g., buttons, text controls, and
checkboxes) within a web page.
 With HTML, you can implement forms and controls, but HTML won’t help you
process the user’s input. To make forms useful, you need to read the user’s input,
process it, and display the results. And to do all that, you need JavaScript.

 FIGURE 8.4 shows a temperature conversion calculator. Note the quantity text
control at the top, the result text control at the bottom, the two list boxes at the sides,
and the convert button in the center.
 All those controls are inside a form. Behind the scenes, the convert button has a
JavaScript event handler.
 When the user clicks the button and submits the form, the event handler code reads
the form’s input values, does the calculation, and displays the result.
 There are two basic strategies for processing a form’s input data. The calculations
may occur on the
 client side (on the browser’s computer) or
 server side (on the web server’s computer).
 With server-side processing, the form input values are transmitted across the Internet
to the server computer. The server then does the calculations and transmits the
answers back to the client computer. The answers are in the form of a new web page
or an updated version of the original web page.
 With client-side processing, there’s no need to go back and forth across the Internet
with user input and generated results. After the web page downloads, the client
computer does all the work. Therefore, client-side processing tends to be faster.
 So normally, you should use client-side processing for relatively simple web
pages.

 Several reasons why server-side processing is sometimes Preferable


1. When the calculations require a lot of programming code. If client-side processing
were used, all the calculation code would have to be downloaded to the client, and
that would slow things down, which can lead to impatient users giving up and going
away
2. When the calculations require the use of large amounts of data, which usually means
using a database. With large amounts of data, you don’t want to have to download it
across the Internet to the browser because that would slow things down. Therefore,
you should keep the data on the server side and do all the processing there.
3. When the code is proprietary. Proprietary code is code that gives the programmer a
competitive advantage. You should keep proprietary code on the server side, where
it’s more difficult for a competitor or hacker to access it.
4. When the inputs and/or calculation results need to be shared by other users. In order
for the data to be shared, it needs to be transmitted to the server so it can be later
transmitted to other users.
5. When user information needs to be processed securely behind the scenes on the
server. ex. credit card numbers and passwords should be processed on the server side.
 The calculations are simple enough that all the programming can be done on the client
side, and client-side would lead to a slightly faster experience, so client-side
processing is preferred.
 Let’s look at a second example web page that uses a form. FIGURE 8.5 shows a web
page that manages the phone numbers for employees at a company. Once again,
should processing take place on the client side or the server side?
 With a large company, there would be a large number of employees, a large amount
of data, and a database would be appropriate, so server-side processing is the way to
go.
 With a small company, there wouldn’t be a large amount of data, but, regardless, you
need to save the data permanently on the server side, so the updated employee phone
data can be viewed later by other users. server-side processing is still the way to go.
[Link] Element

 Which is in charge of grouping a form’s controls. Here’s a template for the form
element’s syntax:

 Note how there’s a submit button control at the bottom and other controls above it.
 That’s probably the most common layout because it encourages the user to first
provide input for the controls at the top before clicking the button at the bottom.
 Notice how this code matches the template provided earlier. The first two controls are
text controls that hold first name and last name user entries.
 The bottom control is a button. When the button is clicked, its onclick event handler
calls the generate Email function that combines the entered first and last names to
form an email address.

Why to use forms?

1. Forms can lead to faster JavaScript processing of the input elements.


2. Forms provide support for being able to check user input to make sure it follows a
particular format. That’s called input validation.
3. Forms provide the ability to add a reset button to assign all the form controls to their
original values.

 To implement a reset button, specify reset for the type attribute, like this:
<input type="reset" value="Reset">

5.12. Controls

 As you can see, most of the controls use the input element for their implementation.
 But just to make things difficult,not all controls use the input element.
 Some important controls use the select and textarea elements.
 FIGURE 8.7, which shows a calendar displayed after the user clicks the down arrow
on the date control’s top-right corner.
 The color control enables the user to select a color from a color picker tool.
 Figure 8.7 shows a color picker displayed after the user clicks the color control’s
black button.
 In Figure 8.6, note the two controls that use the select element—the pull-down
menu and list box controls, both controls allow the user to select an item(s) from a
list of items.
 The pull-down menu control normally displays just one item at a time from the list
and displays the rest of the list only after the user clicks the control’s down arrow.
 On the other hand, the list box control displays multiple list items simultaneously
without requiring the user to click a down arrow.

[Link] Control
 The text control as a box that a user can enter text into.

 The preceding text control template does not include all the attributes for a text control
—just the more important ones.

 The text control is for storing a Social Security number, so the id attribute’s ssn value is
an abbreviation for Social Security number. What’s the purpose of the nine #’s for the
placeholder attribute? Social Security numbers have nine digits, so the nine #’s
implicitly tell the user to enter nine digits with no hyphens.
 Attributes
 Here are the text control attributes

 The type attribute specifies the type of control. For a text control, use type="text". The
default value for the type attribute is text, so if you omit the type attribute, you’ll get a
text control.
 The id attribute’s value serves as an identifier for the text control, so it can be accessed with
JavaScript.
 The placeholder attribute provides a word or a short description that helps the user to know
what to enter into the text control. When the page loads, the browser puts the placeholder’s
value in the text control.
 The size attribute specifies the text control’s width, where the width value is an integer that
approximates the number of average-size characters that can fit in the box. So size="5" means
approximately 5 characters could display in the box simultaneously. The default size is 20.
 The maxlength attribute specifies the maximum number of characters that can be
entered in the box. By default, an unlimited number of characters is allowed. Entries
that exceed the box’s width cause input scrolling to occur.

5. 14. Accessing a Form’s Control Values

 The Email Address Generator’s button event handler passes its form object to the
generateEmail function by using [Link].
 Therefore, to receive the form object passed to the generateEmail function, there’s a
form parameter in the function’s heading as:
function generateEmail(form)
 Figure 8.9B shows the head container for the Email Address Generator web page. Note
the form parameter in the generateEmail function’s heading.
 Within the generateEmail function body, we use the form parameter to retrieve the text
control user inputs. Here’s the code for retrieving the user input from the first-name text
control:

[Link]["first"].value

 To access the controls that are within a form, we use the form object’s elements
property.
 The elements property holds a collection of controls, where a collection is a group of
items that are of the same type.
 To access a control within the elements collection, you put quotes around the
control’s id value and surround the quoted value with []’s.
 So in the preceding code, you can see first within the []’s, and first is the value for the
control’s id attribute.
 As an alternative to using [Link]["first"], you can use form["first"].
 JavaScript Object properties and HTML element attributes
 In the [Link]["first"].value code fragment shown in the previous section, the
value property returns the text control’s user-entered value.
 Having a corresponding JavaScript value property for the HTML value attribute is
indicative of a pattern.
 There’s a parallel world between JavaScript properties and HTML element attributes.
 The presentation of the text control element’s syntax, showed these text control
element attributes:
type, placeholder, size, maxlength, value, autofocus, disabled, readonly
 Here are the corresponding JavaScript properties for a text control element object.
 HTML attributes use all lowercase, whereas JavaScript properties use camel case,
which means the two-word properties are spelled maxLength and readOnly.
 Get used to that weirdness—use all lowercase for HTML attributes, but camel case
for JavaScript properties. JavaScript is case sensitive.
 Control elements’ innerHTML property
 In the Email Address Generator web page’s generateEmail function, the goal is to
update the following p element by replacing its empty content with a generated email
address:

 Retrieve the p element’s object and then use its innerHTML property, like this:
[Link]("email").innerHTML
 The outerHTML accesses the control element’s code, including its start and end tags.
The innerHTML property accesses the content within the control element’s code, not
including its start and end tags.
 In the generateEmail function, here’s the assignment statement that uses innerHTML
to update the p element with a generated email address:

 To connect a string to something else (e.g., another string, a number), you need to use
the concatenation operator, +.
 The resulting connected value forms a string. So in the preceding assignment
statement, the three concatenation operations form a single string, and that string gets
assigned into the innerHTML part of the retrieved p element.

5.15. reset and focus Methods

 In figure 8.9B, the last two lines in the generateEmail function. Here are those lines:
[Link]();
[Link]["first"].focus();
 The form object’s reset method reassigns the form’s controls to their original values.
 Because the Email Address Generator web page has no value attributes for its text
controls, the reset method call assigns empty strings to the text controls, thereby blanking
them out.
 When an element object calls the focus method, the browser puts the focus on the
element’s control if it’s possible to do so.
 For text control elements, like the first-name text control retrieved in the preceding code,
putting the focus on it means the browser positions the cursor in the text control.

Q.1. List some of the more popular controls and the elements used to implement them.
[10 M]
Solution:
1. Text Box
 Element: <input type="text">
 Purpose: Accepts a single line of user input, such as name, address, or email.
 Usage: Most common control in forms.
 Example:
<label>Username: <input type="text" name="username" placeholder="Enter your
name"></label>

 Features:
o Can set maxlength, placeholder, required, and more.
o Can retrieve value in JavaScript: [Link][0].[Link]

2. Password Field

 Element: <input type="password">


 Purpose: Used to hide the characters entered by the user for privacy (e.g., login
forms).
 Example:
<label>Password: <input type="password" name="pass"></label>

 Features:
o Characters appear as dots or asterisks.
o Secure input (though not encrypted by default—server-side security is also
needed).

3. Radio Buttons

 Element: <input type="radio">


 Purpose: Allows selection of only one item from a group.
 Example:
<p>Select Gender:</p>
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female

 Key Point:
o All radio buttons in a group must share the same name.

4. Checkboxes

 Element: <input type="checkbox">


 Purpose: Allows user to select multiple options from a list.
 Example:
<p>Select Skills:</p>
<input type="checkbox" name="skill" value="html"> HTML
<input type="checkbox" name="skill" value="css"> CSS
<input type="checkbox" name="skill" value="js"> JavaScript

5. Text Area

 Element: <textarea>
 Purpose: Used for multi-line text input (e.g., feedback, comments).
 Example:
<textarea name="comments" rows="5" cols="30">Write your comments
here...</textarea>

6. Drop-down List (Select Box)

 Element: <select>, <option>


 Purpose: Presents a list of predefined options in a compact menu.
 Example:
<label>Select Course:
<select name="course">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="js">JavaScript</option>
</select>
</label>

7. Button

 Element: <button> or <input type="button">


 Purpose: Triggers a JavaScript function or event (e.g., alert, validation).
 Example:
<button onclick="alert('Welcome!')">Click Me</button>

8. Submit Button

 Element: <input type="submit">


 Purpose: Submits the form data to the server or another script.
 Example:
<input type="submit" value="Submit Form">

9. Reset Button

 Element: <input type="reset">


 Purpose: Clears all form fields and resets them to their initial values.
 Example:
<input type="reset" value="Reset Form">

Q.2. Describe the functions of javascript. [8M]

Solution:

 JavaScript is a client-side scripting language that allows developers to create


interactive, dynamic, and responsive web pages.
 Several JavaScript functions and concepts are introduced that play vital roles in web
programming.

JavaScript functions:

 Writing reusable blocks of logic (function keyword)


 Handling events (like onclick)
 Accessing/modifying the DOM
 Validating and processing form data
 Enhancing interactivity of webpages

✅ 1. Creating Functions

 A function is a reusable block of code that performs a specific task.


 Functions can be declared and called anywhere in the script.

Syntax:
function greet() {
alert("Welcome to Web Programming!");
}

Usage: <button onclick="greet()">Click Me</button>


✅ 2. User Interaction with Events

 JavaScript functions are often used to handle events such as clicking a button, moving
the mouse, or submitting a form.

Example:
function showMessage() {
alert("Button was clicked!");
}

Usage: <button onclick="showMessage()">Click</button>

✅ 3. Accessing and Modifying HTML (DOM Manipulation)

 JavaScript uses the Document Object Model (DOM) to access and modify HTML
elements dynamically.

Example:
function changeText() {
[Link]("demo").innerHTML = "Text has changed!";
}
Usage: <p id="demo">Original Text</p>
<button onclick="changeText()">Change</button>

✅ 4. Validating Forms

 JavaScript functions are used to validate user inputs before submission to the server,
enhancing user experience and security.

Example:
function validateForm() {
let x = [Link]["myForm"]["username"].value;
if (x === "") {
alert("Username must be filled out");
return false;
}
}
Usage: <form name="myForm" onsubmit="return validateForm()">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>

✅ 5. Mathematical Calculations and Logic

 JavaScript functions perform calculations, decision-making (using if-else), and


iterations (loops).
Example:

function calculateSum(a, b) {
return a + b;
}
let result = calculateSum(10, 20); // result = 30

✅ 6. Working with Form Controls

 JavaScript functions can access form elements and modify their values.

Example:
function getFormValue() {
let name = [Link]("uname").value;
alert("Entered name: " + name);
}
Usage: <input type="text" id="uname">
<button onclick="getFormValue()">Show Name</button>

✅ 7. Built-in Methods like focus() and reset()

 focus() sets the focus to an input field.


 reset() clears all fields in a form.

Example:

[Link]("uname").focus(); // Places cursor in the field


[Link]("myForm").reset(); // Resets form

Q.3. List the advantages of javascript. [8M]

Solution:

 JavaScript is a powerful client-side scripting language that enhances web pages by


making them interactive, dynamic, and user-friendly.
 The following are some key advantages of using JavaScript:

1. 🌐 Client-Side Execution

 JavaScript runs directly in the web browser, reducing the load on the server.
 Faster response time for the user since no server call is needed for simple tasks like
input validation or content updates.
2. 🧠 Easy to Learn and Use

 The syntax of JavaScript is simple and similar to C, making it easy for beginners to
grasp.
 Integrated directly into HTML pages using the <script> tag.

3. ⚡ Interactive Web Pages

 JavaScript allows developers to add interactivity to HTML pages (e.g., dropdowns,


forms, image sliders, and games).
 It enables dynamic content updates without page reload (e.g., hiding/showing
elements, changing text/images).

4. 🧩 Versatile and Flexible

 JavaScript works across all major browsers and is compatible with many
frameworks and libraries (e.g., React, Angular, jQuery).
 It supports both procedural and object-oriented programming.

5. 🔁 Real-Time Feedback to Users

 JavaScript provides immediate feedback, such as form validation before submission.


 Helps in preventing unnecessary server requests.

6. 🔧 Control Over Web Browser and HTML DOM

 JavaScript can access and manipulate the Document Object Model (DOM) to
change page content and structure dynamically.
 Example: Changing text, color, images, styles, or form values on the fly.

7. 📱 Supports Rich Interfaces

 Enables the creation of drag-and-drop interfaces, sliders, tabs, pop-ups, and modal
windows.
 Enhances user experience without needing plugins.

8. 🔒 Reduces Server Load


 Because many validations and interactions are done on the client side, fewer requests
need to be sent to the server, saving bandwidth and processing time.

Summary Table
Advantage Description

Client-Side Execution Fast and efficient without server interaction

Simple and Easy to Use Beginner-friendly syntax

Enhances User Interaction Enables dynamic, responsive web pages

DOM Manipulation Real-time content update without page reload

Immediate Feedback Form validation and alerts

Rich UI Support Sliders, pop-ups, drag & drop, etc.

Asynchronous Data Handling (AJAX) Background data loading

Reduces Server Load Performs tasks locally in the browser

Q.4. What are Javascript events? Explain Event Handler approaches and Event Types.
[10 M]

Solution:

 Event handlers are functions that define what should happen when a particular event
occurs. JavaScript provides three main approaches to handle events:

 JavaScript events make websites interactive by responding to user actions.


 Event handlers are used to define what should happen when events occur.
 Three approaches: Inline, DOM Level 0, and DOM Level 2 (addEventListener).
 Events are classified into various types: mouse, keyboard, form, window, input, etc.

✅ 1. Inline Event Handling (HTML Attribute)

 Event is directly written inside the HTML tag using attributes like onclick,
onchange, etc.

Example:
<button onclick="showMessage()">Click Me</button>
<script>
function showMessage() {
alert("Button Clicked!");
}
</script>

✅ 2. DOM Level 0 (Traditional JavaScript)

 Uses JavaScript to assign a function to an event using DOM element properties.

Example:
<button id="btn">Click</button>

<script>
[Link]("btn").onclick = function () {
alert("Clicked using DOM Level 0");
};
</script>

✅ 3. DOM Level 2 (Modern Method using addEventListener)

 Uses addEventListener() to attach multiple event listeners to a single element.


More powerful and flexible.

Example:

<button id="btn2">Click</button>

<script>
[Link]("btn2").addEventListener("click", function () {
alert("Handled with addEventListener");
});
</script>

📚 Types of JavaScript Events

Below are the main categories of JavaScript events with examples:

Event Type Event Name Description

onclick, onmouseover, onmouseout,


Mouse Events Triggered by mouse actions
ondblclick

Keyboard
onkeydown, onkeypress, onkeyup Triggered by key press
Events

Form Events onsubmit, onreset, onfocus, onblur, Triggered by form interactions


Event Type Event Name Description

onchange

Related to window loading or


Window Events onload, onunload, onresize, onscroll
resizing

Clipboard When text is copied, cut, or


oncopy, oncut, onpaste
Events pasted

Input Events oninput, onchange Detect changes in input fields

✅ Example Combining All:


<form onsubmit="return validateForm()">
<input type="text" id="username" onfocus="highlight(this)">
<input type="submit" value="Submit">
</form>

<script>
function validateForm() {
let user = [Link]("username").value;
if (user === "") {
alert("Username is required");
return false;
}
return true;
}

function highlight(x) {
[Link] = "lightyellow";
}
</script>

Q.5. Write javascript code to print " VTU BELGAUM" using [Link]( ), alert( ) and
[Link]( ). [6M]

Solution:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript Output Example</title>
</head>
<body>

<script>
// Print using [Link]()
[Link]("VTU BELGAUM");
// Print using alert()
alert("VTU BELGAUM");

// Print using [Link]()


[Link]("VTU BELGAUM");
</script>
</body>
</html>

🧾 Explanation:
 [Link]() → Prints output to the browser’s developer console (used for
debugging).
 alert() → Displays a popup alert box with the message.
 [Link]() → Writes the output directly to the HTML page.

Q.6. To implement a rollover with Javascript, what two event-handler attributes should
use? Give suitable example. [10 M]

Solution:

 A rollover effect is a dynamic change in the appearance of a web element—usually


an image or text—when the user moves the mouse over it and restores it when the
mouse moves away.
 It enhances the interactivity and visual appeal of a webpage.
 JavaScript enables this effect using event-handler attributes.

✅ Two Important Event-Handler Attributes


Attribute Description

onmouseover Triggers when the user moves the mouse over an element.

onmouseout Triggers when the user moves the mouse pointer away from the element.

These two events are often used together to create a complete rollover interaction.

🌐 Example: Image Rollover


<!DOCTYPE html>
<html>
<head>
<title>Image Rollover Example</title>
</head>
<body>

<h2>JavaScript Rollover Effect</h2>


<!-- Image that changes on mouse hover -->
<img src="[Link]"
onmouseover="[Link]='[Link]';"
onmouseout="[Link]='[Link]';"
alt="Hover Button" width="200" height="100">

</body>
</html>

🧾 Explanation:

1. Initial Image: [Link] is shown when the page loads.


2. onmouseover: When the mouse pointer hovers over the image, JavaScript changes
the src to [Link].
3. onmouseout: When the mouse pointer leaves the image, it changes back to
[Link].

📝 Alternative Example: Text Rollover


<p onmouseover="[Link]='red';"
onmouseout="[Link]='black';">
Hover over this text to change its color.
</p>

✅ Explanation:

 The text color changes to red on hover, and reverts back when the mouse moves
away.

🎯 Where Rollovers Are Used:

 Navigation menus
 Image galleries
 Buttons with hover effects
 Interactive banners
 Product previews

📌 Summary
Feature Details

A change in appearance when the mouse moves over an


What is Rollover?
element.

Main Attributes Used onmouseover, onmouseout


Feature Details

Common Elements Affected Images, text, links

Why Use It? To improve interactivity and user experience


Q.7. Explain the advantages and disadvantages of client side scripting. [8M]
Solution:
Client-side scripting refers to scripts that run on the user's browser (client-side) instead of
the web server. Common client-side scripting languages include JavaScript, HTML, and
CSS.

🌟 Advantages of Client-Side Scripting


Advantage Description

Since scripts run on the user's local browser, actions are performed
1. Fast Execution
quickly without waiting for a server response.

2. Reduces Server Basic tasks like input validation, interactivity, and dynamic UI changes
Load are handled by the browser, reducing the burden on the server.

3. Enhanced User Immediate feedback, dynamic updates (like drop-downs, tooltips), and
Experience interactivity improve usability.

Some features can run even without an internet connection after the
4. Offline Execution
page is loaded.

Errors and outputs can be viewed easily using browser developer tools
5. Easy Debugging
(e.g., [Link]() in JavaScript).

⚠️Disadvantages of Client-Side Scripting


Disadvantage Description

Scripts may not work the same in all browsers due to differences
1. Browser Compatibility
in support and behavior.

Code is visible to users and can be tampered with or misused. It


2. Security Risks
cannot be trusted for sensitive operations.

Users can disable JavaScript in their browser, which can break


3. Disabled Scripting
site functionality.

4. Limited Access to Client-side scripts cannot access files or hardware for security
System Resources reasons.

5. Cannot Replace Server- Cannot handle tasks like database access, authentication, or file
Side Logic processing — these require server-side scripting.
✍️Summary Table
🔷 Advantages 🔶 Disadvantages

Fast and efficient Browser dependency

Low server load Security vulnerabilities

Better interactivity Can be disabled by users

Supports dynamic content Cannot perform server-level tasks

Enhances UX and responsiveness Limited system-level access

You might also like