JavaScript Basics: Functions and DOM
JavaScript Basics: Functions and DOM
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:
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.
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.
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
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.
function function-name(zero-or-more-parameters-separated-bycommas)
{
statement-1;
statement-2;
…
last-statement;
}
Normally, function definitions should be placed
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:
What type of value is 158? A number, since a number consists of digits with an
optional decimal point.
5.7. Identifiers
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,
When the user clicks the button. To understand how that works, we need to talk about
assignment statements and objects.
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.
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]
[Link]("message")
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).
(1) an element,
(2) a text item that appears between an element’s start and end tags,
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
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.
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.
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.
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.
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
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
Key Point:
o All radio buttons in a group must share the same name.
4. Checkboxes
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>
7. Button
8. Submit Button
9. Reset Button
Solution:
JavaScript functions:
✅ 1. Creating Functions
Syntax:
function greet() {
alert("Welcome to Web Programming!");
}
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!");
}
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>
function calculateSum(a, b) {
return a + b;
}
let result = calculateSum(10, 20); // result = 30
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>
Example:
Solution:
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.
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.
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.
Enables the creation of drag-and-drop interfaces, sliders, tabs, pop-ups, and modal
windows.
Enhances user experience without needing plugins.
Summary Table
Advantage Description
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:
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>
Example:
<button id="btn">Click</button>
<script>
[Link]("btn").onclick = function () {
alert("Clicked using DOM Level 0");
};
</script>
Example:
<button id="btn2">Click</button>
<script>
[Link]("btn2").addEventListener("click", function () {
alert("Handled with addEventListener");
});
</script>
Keyboard
onkeydown, onkeypress, onkeyup Triggered by key press
Events
onchange
<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");
🧾 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:
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.
</body>
</html>
🧾 Explanation:
✅ Explanation:
The text color changes to red on hover, and reverts back when the mouse moves
away.
Navigation menus
Image galleries
Buttons with hover effects
Interactive banners
Product previews
📌 Summary
Feature Details
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).
Scripts may not work the same in all browsers due to differences
1. Browser Compatibility
in support and behavior.
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