JavaScript Basics in HTML Examples
JavaScript Basics in HTML Examples
OR
<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript in HTML Example</title>
<script>
// This is a JavaScript function
function showMessage()
{
alert('Hello! This is a message from JavaScript.');
}
</script>
</head>
<body>
<h1>Hello, World!</h1>
<p>Click the button to see a message.</p>
Explanation:
1. HTML Structure: The basic structure of the HTML document is defined using the <!DOCTYPE html> declaration,
followed by the <html>, <head>, and <body> tags.
2. JavaScript in the <script> Tag: JavaScript code is placed inside the <script> tag. In this example, the function
showMessage() is defined within this tag.
3. Event Handling: The onclick attribute in the <button> element is used to trigger the showMessage() function
when the button is clicked.
4. Alert Function: The alert() method is used to display a simple message in a dialog box.
<script>
[Link]("message").innerHTML = "Hello, World!";
</script>
</body>
</html>
Explanation:
• The [Link]("message").innerHTML changes the content of the paragraph with the ID
message.
• This program displays "Hello, World!" in the paragraph tag (<p>), demonstrating how to modify HTML
content using JavaScript.
<script>
let a = 10;
let b = 5;
let sum = a + b;
[Link]("result").innerHTML = "The sum of " + a + " and " + b + " is " + sum;
</script>
</body>
</html>
<div id="results"></div>
<script>
function performOperations()
{
var num1 = parseFloat([Link]('num1').value);
var num2 = parseFloat([Link]('num2').value);
Explanation:
HTML Structure:
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operations</title>
</head>
<body bgcolor=" #d7bde2 ">
<h1>Arithmetic Operations</h1>
• The code starts with the <!DOCTYPE html> declaration, which defines the document as an HTML5 document.
• The <head> section includes a <title> tag that sets the title of the webpage as "Arithmetic Operations."
• The <body> tag has a bgcolor attribute set to " #d7bde2 ", which changes the background color of the page
to cyan.
• The <h1> tag is used to create a heading that reads "Arithmetic Operations."
• Two labels and input fields are provided for the user to enter the first and second numbers.
• The <label> tag associates’ text with the corresponding input field.
• The <input> tags have type="number", which ensures that only numeric input is allowed.
• Each input field is assigned a unique id (num1 and num2) so that they can be referenced in the JavaScript
code.
• <br/> tags are used to add line breaks for spacing between the elements.
• An empty <div> with the id="results" is provided to display the results of the arithmetic operations. The
results will be dynamically inserted here by the JavaScript code.
JavaScript Code:
<script>
function performOperations()
{
var num1 = parseFloat([Link]('num1').value);
var num2 = parseFloat([Link]('num2').value);
Arithmetic Operations:
var addition = num1 + num2;
var subtraction = num1 - num2;
var multiplication = num1 * num2;
var division = num1 / num2;
var modulo = num1 % num2;
"<p>Division: " + num1 + " / " + num2 + " = " + division + "</p>" +
"<p>Modulo: " + num1 + " % " + num2 + " = " + modulo + "</p>";
}
</script>
• The results variable is assigned the <div> element with the id="results".
• The innerHTML property of the results div is set to a string that includes the HTML for displaying the results
of the arithmetic operations.
• Each operation's result is displayed using a series of <p> tags, with the operation details and results included.
• The + operator is used to concatenate strings and variables.
Summary:
• User Interaction: The user inputs two numbers and clicks the "Perform Operations" button.
• Functionality: The JavaScript function performOperations() retrieves the input values, performs the
arithmetic operations, and displays the results within the webpage.
• Display: The results are shown in a formatted and color-coded section below the input fields.
<button onclick="calculateCircle()">Calculate</button>
<div id="circleResults"></div>
<script>
function calculateCircle() {
var radius = parseFloat([Link]('radius').value);
Explanation:
• Input: The user inputs the length and width of the rectangle.
• Output: The area and perimeter of the rectangle are calculated and displayed.
General Structure:
• HTML Structure: Both programs have a similar structure with <label> and <input> elements for user inputs, a
<button> to trigger the calculation, and a <div> to display the results.
• JavaScript: The functions calculateCircle() and calculateRectangle() handle the respective calculations. The
results are dynamically displayed in the corresponding <div> elements using innerHTML. The calculations are
formatted and presented clearly to the user.
These examples should provide a good foundation for creating similar programs that involve basic arithmetic
calculations.
<div id="areaResult"></div>
<script>
function calculateArea() {
// Get values from the input fields
const baseValue = parseFloat([Link]('base').value);
const heightValue = parseFloat([Link]('height').value);
Explanation:
1. HTML Structure:
o The <label> and <input> tags are used to create fields where the user can enter the base and height of
the triangle.
o The type="number" attribute in the <input> tags ensures that the input is numeric.
2. Button:
o The <button> tag is used to create a "Calculate Area" button.
o When the button is clicked, it triggers the calculateArea() function.
3. JavaScript Function:
o The calculateArea() function retrieves the values entered by the user for the base and height using
[Link]().value.
o It calculates the area of the triangle using the formula (base * height) / 2.
o The result is displayed within the areaResult <div> on the page.
o The .toFixed(2) method is used to format the area to two decimal places for better readability.
4. Display:
o The area of the triangle is displayed directly on the webpage under the input fields after the user clicks
the "Calculate Area" button.
This structure provides a user-friendly interface for calculating the area of a triangle, with the result displayed
immediately on the page.
If you know all the sides of a triangle, you can find the area using Herons' formula. If a, b and c are the three sides
of a triangle, then
s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))
<!DOCTYPE html>
<html>
<head>
<title>Triangle Area Calculator (Heron's Formula)</title>
</head>
<body bgcolor="#d7bde2">
<h1>Calculate the Area of a Triangle using Heron's Formula</h1>
<div id="areaResult"></div>
<script>
function calculateTriangleArea() {
// Get the values of the three sides from the input fields
const side1 = parseFloat([Link]('side1').value);
const side2 = parseFloat([Link]('side2').value);
const side3 = parseFloat([Link]('side3').value);
<p id="result"></p>
<script>
function checkNumber() {
// Program that checks if the number is positive, negative or zero
// Input from the user
const number = parseInt(prompt("Enter a number: "));
Explanation:
This program is an interactive web application that allows the user to check whether a number is positive,
negative, or zero. Here's a detailed explanation of how it works:
1. DOCTYPE Declaration:
<!DOCTYPE html>: This tells the browser that the document is an HTML5 document.
3. Body Section:
o <body>: Contains the visible content of the webpage.
o <h1>: Displays the main heading of the page, "Check if a Number is Positive, Negative, or Zero".
o <button>: Creates a button labeled "Enter a Number". When this button is clicked, it triggers the
checkNumber() function.
o <p id="result"></p>: This paragraph will be used to display the result of the check (whether the number
is positive, negative, or zero). Initially, it is empty.
JavaScript Function:
1. Function Definition:
The <script> tag encloses the JavaScript code that adds interactivity to the webpage.
2. checkNumber() Function:
Prompt for Input:
▪ const number = parseInt(prompt("Enter a number: "));: This line prompts the user to enter a number. The
prompt() function opens a dialog box asking the user to input a number. The parseInt() function converts
the input from a string to an integer.
Conditional Logic:
▪ The if...else if...else structure checks the value of the input number and assigns an appropriate message
to the message variable.
▪ if (number > 0): If the number is greater than 0, the message is "The number is positive".
▪ else if (number === 0): If the number is equal to 0, the message is "The number is zero". The ===
operator is used to check for strict equality.
▪ else: If the number is less than 0, the message is "The number is negative".
3. Output:
o The program displays the result below the button in the <p> element with the id="result". The result will
be one of three possible messages: "The number is positive", "The number is zero", or "The number is
negative".
button {
padding: 5px 10px;
font-size: 16px;
margin-left: 10px;
cursor: pointer;
}
#result {
margin-top: 20px;
font-weight: bold;
font-size: 20px;
}
.positive {
color: green;
}
.negative {
color: red;
}
.zero {
color: blue;
}
</style>
</head>
<body bgcolor=cyan>
<h1>Check if a Number is Positive, Negative, or Zero</h1>
<p id="result"></p>
<script>
function checkNumber() {
// Get the value from the textbox
const number = parseInt([Link]("numberInput").value);
<div id="factorialResult"></div>
<script>
function calculateFactorial() {
// Get the input value
const number = parseInt([Link]('number').value);
Explanation:
1. HTML Structure:
• Input Field:
The user can enter a positive integer in the input field (<input type="number" id="number">).
• Button:
The "Calculate Factorial" button triggers the calculateFactorial() function when clicked.
• Result Display:
The result will be displayed in the <div id="factorialResult"></div> element on the page.
2. JavaScript Function:
• Input Retrieval:
The number is retrieved from the input field using [Link]('number').value and converted
to an integer using parseInt().
• Conditional Logic:
▪ Negative Number Check:
If the entered number is negative, an error message is displayed ('Error! Factorial for negative
number does not exist.').
▪ Zero Check:
If the number is 0, the factorial is 1 ('The factorial of 0 is 1.').
▪ Positive Number:
o For positive numbers, a for loop calculates the factorial by multiplying numbers from 1 to the
entered number.
o The calculated factorial is displayed in the result message.
• Displaying the Result:
The result is displayed on the webpage in the factorialResult <div> using innerHTML.
How It Works:
1. User Interaction:
The user enters a positive integer and clicks the "Calculate Factorial" button.
2. Calculation:
The JavaScript function processes the input to check if it’s negative, zero, or positive, and then calculates the
factorial accordingly.
3. Output:
The result (factorial of the entered number) or an error message is displayed on the webpage.
[Link] Calculator:
<!DOCTYPE html>
<html>
<head>
<title>Simple Calculator</title>
</head>
<body bgcolor="#d7bde2">
<h1>Simple Calculator</h1>
<button onclick="calculate()">Calculate</button>
<div id="calculatorResult"></div>
<script>
function calculate() {
// Get the values from the input fields
const number1 = parseFloat([Link]('number1').value);
const operator = [Link]('operator').value;
const number2 = parseFloat([Link]('number2').value);
let result;
Explanation:
1. HTML Structure:
Input Fields:
Three input fields are provided:
1. For the first number (<input type="number" id="number1">).
2. For the operator (<input type="text" id="operator">).
3. For the second number (<input type="number" id="number2">).
Button:
A "Calculate" button triggers the calculate() function when clicked.
Result Display:
The result of the calculation is displayed in the <div id="calculatorResult"></div> element on the page.
2. JavaScript Function:
Input Retrieval:
The numbers and the operator are retrieved from their respective input fields.
Conditional Logic:
The program checks the value of the operator to determine which arithmetic operation to perform:
1. + for addition.
2. - for subtraction.
3. * for multiplication.
4. / for division.
If the operator is not one of the four valid options, the program returns "Invalid operator".
3. How It Works:
▪ The user inputs two numbers and an operator.
▪ The "Calculate" button triggers the calculation based on the operator provided.
▪ The result of the calculation is displayed on the webpage.
<body bgcolor="#d4efdf">
<h1>Multiplication Table Generator</h1>
<div id="multiplicationTable"></div>
<script>
function generateTable() {
// Get the input value
const number = parseInt([Link]('number').value);
Explanation:
1. HTML Structure:
o Input Field:
The user can input an integer in the input field (<input type="number" id="number">).
o Button:
The "Generate Table" button triggers the generateTable() function when clicked.
o Result Display:
The multiplication table will be displayed in the <div id="multiplicationTable"></div> element on the
page.
2. JavaScript Function:
o Input Retrieval:
The number is retrieved from the input field using [Link]('number').value and
converted to an integer using parseInt().
o Generating the Multiplication Table:
▪ A for loop iterates from 1 to 10, multiplying the input number by the loop variable i.
▪ The result of each multiplication is appended to the table string variable, which will store the entire
multiplication table.
3. How It Works:
o The user inputs an integer and clicks the "Generate Table" button.
o The generateTable() function creates the multiplication table for that number.
o The table is displayed on the webpage.
This program allows users to generate a multiplication table for any integer they enter, directly on the webpage.
<div id="multiplicationTable"></div>
<script>
function generateTable() {
// Get the input values
const number = parseInt([Link]('number').value);
const range = parseInt([Link]('range').value);
</body>
</html>
Explanation:
1. HTML Structure:
o Input Fields:
▪ The user can input an integer in the input field (<input type="number" id="number">).
▪ The user can also input a range in the second input field (<input type="number" id="range">).
o Button:
▪ The "Generate Table" button triggers the generateTable() function when clicked.
o Result Display:
▪ The multiplication table will be displayed in the <div id="multiplicationTable"></div> element on the
page.
2. JavaScript Function:
o Input Retrieval:
▪ The number and the range are retrieved from their respective input fields using
[Link]('number').value and [Link]('range').value, and
converted to integers using parseInt().
o Generating the Multiplication Table:
▪ A for loop iterates from 1 to the specified range, multiplying the input number by the loop variable i.
▪ The result of each multiplication is appended to the table string variable, which will store the entire
multiplication table.
o Displaying the Result:
▪ The generated multiplication table is displayed on the webpage in the multiplicationTable <div>
using innerHTML.
3. How It Works:
o The user inputs an integer and a range, then clicks the "Generate Table" button.
o The generateTable() function creates the multiplication table for that number up to the specified range.
o The table is displayed on the webpage.
This program allows users to generate a multiplication table for any integer they enter, up to a specified range,
directly on the webpage.