Java Script
Java Script
Java Script
0. Overview:
JavaScript is a versatile programming language primarily used for front-end web development, but it has
expanded its reach to various other domains, including server-side development (Node.js), mobile app development,
and even desktop applications. Here's an overview of JavaScript:
• JavaScript was initially created to add interactivity and dynamic behaviour to web pages.
• It is commonly used for client-side scripting to enhance user interfaces and respond to user actions
on websites.
2. Execution Environment:
• JavaScript is primarily executed by web browsers, allowing developers to create interactive and
dynamic content on the client side.
• With the introduction of Node.js, JavaScript can also be used for server-side development,
enabling full-stack development using a single language.
3. Syntax:
• JavaScript syntax is similar to other C-style languages like Java and C++, making it relatively easy
for developers to learn if they are familiar with these languages. Codes will be give inside a <script>
tag or as separate script file.
• It is an interpreted language, and the source code is executed by the JavaScript engine in the
browser or server environment.
4. Data Types:
• JavaScript supports various data types, including numbers, strings, booleans, objects, arrays, and
functions.
5. Dynamic Typing:
• JavaScript is dynamically typed, meaning that variable types are determined at runtime. This
provides flexibility but requires careful handling to avoid unexpected behaviour.
6. Functions:
• Functions are a fundamental part of JavaScript. They can be defined, assigned to variables, passed
as arguments, and returned as values.
7. Event-Driven Programming:
• JavaScript is often used in an event-driven paradigm, where actions or events trigger specific
functions or behaviours. This is crucial for creating interactive web pages.
8. DOM Manipulation:
• The Document Object Model (DOM) is a programming interface for web documents. JavaScript is
commonly used to manipulate the DOM, enabling dynamic changes to the structure and content
of web pages.
9. Asynchronous Programming:
• JavaScript uses an asynchronous, non-blocking execution model. This is essential for handling tasks
like AJAX requests, animations, and other operations that should not block the main thread.
• There are numerous libraries and frameworks built on top of JavaScript, such as jQuery, React,
Angular, and Vue.js, which simplify and streamline web development tasks.
In JavaScript, a variable is a container for storing data values. Variables are used to store and manipulate
information in a program. You can think of a variable as a named storage location that holds a value, and this value can
be changed during the execution of a program.
In JavaScript, there are three ways to declare variables: var, let, and const.
• var: This was the original way to declare variables in JavaScript, but it has some issues and is now less
commonly used. Variables declared with var are function-scoped, which means they are only available
within the function where they are declared.
var x = 10;
• let: Introduced in ECMAScript 6 (ES6), let allows you to declare block-scoped variables. Block-scoped
means the variable is only available within the block (a pair of curly braces) where it is defined.
let y = 20;
• const: Also introduced in ES6, const is used to declare constants. Once a value is assigned to a const
variable, it cannot be reassigned. However, it's important to note that the constantans applies to the
reference in case of objects and arrays, not the value.
const z = 30;
3. Printing values of variables:-
<script>
let name = "Krishnan";
let age = 25;
Syntax → `${var_name}`
<script>
let name = "Krishnan";
let age = 25;
4. HTML example code for all types of values and print using document.write()
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>JavaScript Variables Example</title>
</head>
<body>
<script>
// Using var
var a = “hello”;
document.write(a);
// Using let
let b = ‘a’;
document.write(b);
// Using const
const pi = 3.14;
document.write("<br>" + c);
</script>
</body>
</html>
All these variables can all type of data like integer, float, character, string, JSON.
5.Operators
In programming, an operator is a symbol or keyword that performs operations on one or more operands.
Operators are used to manipulate data and variables in expressions or statements.
The operands can be values, variables, or expressions themselves. The type of operation an operator performs
depends on its functionality and the types of operands it operates on.
Arithmetic operators perform basic arithmetic operations like addition, subtraction, multiplication,
division, and more.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arithmetic Operators</title>
</head>
<body>
<script>
var num1 = 10;
var num2 = 5;
Comparison operators compare values and return a Boolean result (true or false).
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comparison Operators</title>
</head>
<body>
<script>
var num1 = 10;
var num2 = 5;
Logical operators perform logical operations and return a Boolean result (true or false).
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Logical Operators</title>
</head>
<body>
<script>
var condition1 = true;
var condition2 = false;
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Assignment Operators</title>
</head>
<body>
<script>
var x = 5;
document.write("Original value of x: " + x + "<br>");
x -= 2; // Equivalent to x = x - 2;
document.write("After -=: " + x + "<br>");
x *= 4; // Equivalent to x = x * 4;
document.write("After *=: " + x + "<br>");
x /= 2; // Equivalent to x = x / 2;
document.write("After /=: " + x + "<br>");
</script>
</body>
</html>
6.Conditional Statements
Conditional statements in JavaScript are used to make decisions in your code based on certain conditions.
These statements allow your program to execute different blocks of code depending on whether a specified condition
evaluates to true or false. There are several types of conditional statements in JavaScript:
1. if statement:
• The if statement is a basic conditional statement that executes a block of code if a specified condition
is true.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if Statement</title>
</head>
<body>
<script>
// JavaScript code
let num = 10;
if (num > 0) {
document.write("The number is positive");
}
</script>
</body>
</html>
2. if-else statement:
• The if-else statement allows you to specify a block of code to be executed if the condition is true and
another block if the condition is false.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-else Statement</title>
</head>
<body>
<script>
// JavaScript code
let num = -5;
if (num > 0) {
document.write("The number is positive");
}
else {
document.write("The number is not positive");
}
</script>
</body>
</html>
3. if-else if-else statement:
• The if-else if-else statement allows you to check multiple conditions and execute different blocks of
code based on the first true condition.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>if-else if-else Statement</title>
</head>
<body>
<script>
// JavaScript code
let num = 0;
if (num > 0) {
document.write("The number is positive");
}
else if (num < 0) {
document.write("The number is negative");
}
else {
document.write("The number is zero");
}
</script>
</body>
</html>
4. switch statement:
• The switch statement is used to perform different actions based on different conditions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switch Statement</title>
</head>
<body>
<script>
// JavaScript code
let day = "Wednesday"; // Change this to any day of the week
switch (day) {
case "Monday":
document.write("It's the start of the week");
break;
case "Tuesday":
document.write("It's a weekday");
break;
case "Wednesday":
document.write("It's the middle of the week");
break;
case "Thursday":
document.write("It's almost the weekend");
break;
case "Friday":
document.write("It's the end of the week");
break;
case "Saturday":
document.write("It's the weekend");
break;
case "Sunday":
document.write("It's the weekend");
break;
default:
document.write("Invalid day");
}
</script>
</body>
</html>
These examples showcase the use of different conditional statements in JavaScript, each with its specific
purpose. You can embed these JavaScript code snippets in your HTML files to see them in action.
7.Loops
In programming, a loop is a control structure that allows a set of instructions to be repeated multiple times.
Loops are used when you want to execute a block of code repeatedly until a certain condition is met. They help in
automating repetitive tasks and make code more concise.
1. For Loop:
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>For Loop Example</title>
</head>
<body>
<script>
for (let i = 1; i <= 5; i++) {
document.write('Iteration ' + i);
}
</script>
</body>
</html>
2. While Loop:
• A while loop is used to execute a block of code as long as the specified condition is true.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>While Loop Example</title>
</head>
<body>
<script>
let i = 1;
while (i <= 5) {
document.write('Iteration ' + i);
i++;
}
</script>
</body>
</html>
3. Do...While Loop:
• A do...while loop is similar to a while loop, but the block of code is executed at least once, even if
the condition is false.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Do...While Loop Example</title>
</head>
<body>
<script>
let i = 1;
do {
document.write('Iteration ' + i);
i++;
} while (i <= 5);
</script>
</body>
</html>
8.Functions
In JavaScript, a function is a reusable block of code that performs a specific task. Functions help in
organizing code, making it more modular and easier to maintain. Functions can take parameters (input values),
perform operations, and return a result.
Functions can accept parameters, which are variables that hold values passed to the function
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Function with Parameters</title>
</head>
<body>
<script>
// Creating a function with parameters
function greet(name) {
console.log("Hello, " + name + "!");
}
// Calling the function with a parameter
greet("John");
</script>
</body>
</html>
The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a document as a tree-like model where each node corresponds to a part of the document. The DOM
provides a way for scripts to dynamically access, manipulate, and update the content, structure, and style of a
document. Usages of JavaScript as follows,
3. Handling Events:
• Attach event listeners to respond to user interactions (e.g., clicks, key presses, form submissions).
4. Dynamic Styling:
• Change the styles (e.g., color, size, visibility) of HTML elements dynamically.
• Add or remove elements, change their hierarchy, and manipulate the overall structure of the
document.
• Navigate through the document tree, moving from one element to another, and accessing parent,
child, or sibling elements.
• Access and manipulate form elements, validate user input, and handle form submissions.
9.i).Changing element content and inline CSS style using JS DOM method
<!DOCTYPE html>
<html>
<head>
<title>1</title>
</head>
<body>
<p id="p1">i'm a paragraph tag</p>
<button onmouseout="dothat()">Hit Me</button>
<script type="text/javascript">
let ele = document.getElementById("p1");
function dothat(){
ele.style.backgroundColor="green";
ele.style.fontSize="100px";
ele.style.color="white";
ele.style.border="3px dotted blue";
ele.innerText="Content Changed";
}
</script>
</body>
</html>
Explanation
1. HTML Snippet
• Create a paragraph with the id "p1" containing the text "I'm a paragraph tag"
• Create a button with the text "Hit Me" and an onmouseou event that triggers the dothat function
(<button onmouseout="dothat()">Hit Me</button>)
<!DOCTYPE html>
<html>
<head>
<title>Change Attribute</title>
</head>
<body>
<img id="myImage" src="smiley.gif">
<button onclick="changeImage()">Change image</button>
<script>
function changeImage() {
var image = document.getElementById("myImage");
image.setAttribute("src", "landscape.jpg");
image.setAttribute("height", "500px");
image.setAttribute("width", "500px");
}
</script>
</body>
</html>
Explanations: -
1. HTML Snippet
• Create an image with the id "myImage" and the initial source "smiley.gif"
(<img id="myImage" src="smiley.gif">)
• Create a button with the text "Change image" and an onclick event that triggers the changeImage
function
(<button onclick="changeImage()">Change image</button>).
• Use the setAttribute method to change the src attribute value to "landscape.jpg".
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- Input fields for Name and Age -->
<label>Enter Name</label>
<input type="text" id="fn">
<label>Enter Age</label>
<input type="number" id="age">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Element Example</title>
</head>
<body>
<h1>Create Element Example</h1>
<div id="output">
</div>
<script>
var outputDiv = document.getElementById("output");
function createElement1() {
var paragraph = document.createElement("p");
paragraph.textContent = "This is a dynamically created paragraph.";
outputDiv.appendChild(paragraph);
}
</script>
</body>
</html>
Algorithm:-
1. HTML Structure:
2. Page Content:
• <div id="output"></div>: Provides a container with the id "output" where the dynamically created
paragraph will be appended.
3. JavaScript Code:
• <script>: Contains JavaScript code that enhances the functionality of the page.
• paragraph.textContent = "This is a dynamically created paragraph.";: Sets the text content of the
paragraph.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>To-Do’s</title>
<style>
//Add CSS here
</style>
</head>
<body>
<h2>To-Do List Using Unordered List</h2>
<input type="text" id="task">
<button onclick="add()">Add Task</button>
<ul id="list"></ul>
<script>
let parent = document.getElementById('list');
function add() {
// Step 1: Retrieve the task input element
let taskInput = document.getElementById('task');
</script>
</body>
</html>
10. querySelector() and querySelectorAll()
• querySelector():
• querySelector() is a method in JavaScript that allows you to select the first element in the document
that matches a specified CSS selector.
• Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>querySelector</title>
</head>
<body>
<p id="para"></p>
<script>
const element = document.querySelector('#para');
element.innerText = "Hello";
</script>
</body>
</html>
• Explanation:-
• Within the <body> section, create a <p> element with the id attribute set to "para."
• Add a <script> tag within the <body> section to contain JavaScript code.
• Use element.innerText = "Hello" to set the text content of the selected paragraph to
"Hello."
• querySelectorAll():
• querySelectorAll() is similar to querySelector() but returns a NodeList containing all elements that
match the specified CSS selector.
• Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>querySelectorAll</title>
</head>
<body>
<p class="para"></p>
<p class="para"></p>
<p class="para"></p>
<p class="para"></p>
<script>
const elements = document.querySelectorAll('.para');
for (let i = 0; i < elements.length; i++) {
elements[i].innerText = "Hello " + i;
}
</script>
</body>
</html>
• Explanation:
• Include a <meta> tag within the <head> section to set the character encoding (UTF-
8).
• Within the <body> section, create four <p> elements with the class "para."
• Add a <script> tag within the <body> section to contain JavaScript code.
• For each iteration, set the innerText of the current element to "Hello "
followed by the loop index (i).
10.ii) Why Use querySelector() and querySelectorAll()?
• These methods provide a concise and readable way to select elements from the DOM using CSS
selectors, making the code more expressive and maintainable.
• Powerful Selectors:
• CSS selectors are powerful and flexible, allowing for complex queries based on element
attributes, relationships, and more.
• querySelector() is used when you only need the first matching element, while querySelectorAll()
is useful for selecting multiple elements.
10.iii) Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Multiple querySelector</title>
<style>
.highlight {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div id="container">
<p class="highlight">This paragraph is highlighted.</p>
<p>This paragraph is not highlighted.</p>
<ul>
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
</ul>
</div>
<script>
// Selecting by ID
const container = document.querySelector('#container');
container.style.border = '2px solid blue';
// Selecting by class
const hlPar = document.querySelector('.highlight');
hlPar.textContent = 'Now I am modified!';
setTimeout is a JavaScript function that allows you to schedule the execution of a function after a specified
delay in milliseconds. It is commonly used to introduce a delay before executing a particular piece of code or to create
timed intervals.
Example :-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setTimeout Example</title>
</head>
<body>
<h2>setTimeout in JS</h2>
<p id="message"></p>
<script>
// Function to be executed after a delay
function showMessage() {
let p = document.getElementById('message');
p.innerText = 'Hello, this message was delayed! for 3 seconds';
}
Explantion :-
1. The HTML document contains an <h2> heading and a <p> element with the id "message," where the delayed
message will be displayed.
2. The JavaScript code includes a showMessage function that updates the text content of the "message" element.
3. The setTimeout function is then used to schedule the execution of the showMessage function after a delay of
3000 milliseconds (3 seconds).
4. When the page loads, the message will not appear immediately. After the specified delay, the showMessage
function will be executed, updating the content of the "message" element, and the delayed message will be
displayed.
12.Array’s In JS
In JavaScript, an array is a data structure that allows you to store and manipulate a collection of values. Arrays
can hold various types of data, including numbers, strings, objects, and even other arrays. They provide a way to
organize and access elements using numerical indices.
• You can create an array using the array literal notation [].
• Examples:
<script>
// Using []
let fruits = ['Apple', 'Banana', 'Orange'];
</script>
2. Accessing Elements:
• Example:
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits[0]); // Output: apple
</script>
3. Array Length:
• Example:
<script>
let fruits = ['Apple', 'Banana', 'Orange'];
console.log(fruits.length); // Output: 3
</script>
4. Array Methods
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Array Methods</title>
</head>
<body>
<h1>JavaScript Array Methods Example</h1>
<script>
// Sample array
let originalArray = [1, 2, 3, 4, 5];
// 8. indexOf(): Returns the first index at which a given element can be found in the array
let indexOfElement = originalArray.indexOf(10);
console.log("Index of 10:", indexOfElement);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Changing Color</title>
</head>
<body>
<button onclick="change()">Change Background Color</button>
<script>
let color = ["red","blue","green","lightgreen"];
function change(){
let ind = Math.floor(Math.random()*3);
document.body.style.backgroundColor=color[ind];
}
</script>
</body>
</html>
Explanation:-
1. HTML Structure:
• let color = ["red", "blue", "green", "lightgreen"];: Defines an array named color containing
four different color strings.
• function change() { ... }: Defines a JavaScript function named change. This function is called
when the button is clicked.
• The change function generates a random index (ind) and uses it to select a color from the color
array.
• The selected color is then applied as the background color of the body element.
12.ii) Load Multiple images using Array with setTimeout
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Loading Multiple Images using array</title>
</head>
<body>
<img height="300px" width="300px" id="ig">
<script type="text/javascript">
let paths=["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg"];
let init = 0;
function loadimg(){
let i = document.getElementById('ig');
if(init < paths.length){
i.setAttribute("src",paths[init]);
init++;
setTimeout(loadimg,1000);
}
}
loadimg()
</script>
</body>
</html>
1. HTML Structure:
• <h1>Loading Multiple Images using array</h1>: Displays a heading indicating the purpose of the
page.
• <img height="300px" width="300px" id="ig">: Defines an image element with an initial height and
width, and an id of 'ig'.
3. JavaScript Section:
• let paths = [...]: Defines an array named paths containing file paths to multiple images.
• let init = 0;: Initializes a variable init to keep track of the current image being loaded.
• if (init < paths.length) { ... }: Checks if there are more images to load.
• i.setAttribute("src", paths[init]);: Sets the source attribute of the image element to the path
of the current image.
• init++;: Increments the init variable to move to the next image in the array.
• loadimg(): Calls the loadimg function to start loading the images when the page loads.
13. Date Object in JavaScript
The Date object in JavaScript is used for working with dates and times. It provides methods to get and set
various date and time components, such as the year, month, day, hour, minute, second, and milliseconds. The Date
object is particularly useful for handling operations involving dates, such as calculating durations, formatting dates
for display, and working with time intervals.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Object Methods</title>
</head>
<body>
<h1>Date Object Methods Example</h1>
<script>
// Create a new Date object
let currentDate = new Date();
// Formatting date
let formattedDate = currentDate.toDateString();
document.write("<p>Formatted Date: " + formattedDate + "</p>");
</script>
</body>
</html>
13.i) Age Calculator using Date object;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Age Calculator</title>
</head>
<body>
<h1>Age Calculator</h1>
<label for="birthdate">Enter your birthdate:</label>
<input type="date" id="birthdate">
<button onclick="calculateAge()">Calculate Age</button>
<p id="result"></p>
<script>
function calculateAge() {
const birthdateString = document.getElementById("birthdate").value;
const birthdate = new Date(birthdateString);
const currentDate = new Date();
<script>
function updateClock() {
const currentTime = new Date();
const hours = currentTime.getHours().toString().padStart(2, '0');
const minutes = currentTime.getMinutes().toString().padStart(2, '0');
const seconds = currentTime.getSeconds().toString().padStart(2, '0');
The Math object provides methods for performing common mathematical operations like rounding,
exponentiation, trigonometry, and more. It also includes mathematical constants like π (pi) and Euler's number (e).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Math Object Examples</title>
</head>
<body>
<h1>Math Object Examples</h1>
<h2>Math Constants:</h2>
<p>π (Pi): <span id="pi"></span></p>
<p>e (Euler's Number): <span id="euler"></span></p>
<h2>Trigonometric Functions:</h2>
<p>Sine: <span id="sine"></span></p>
<p>Cosine: <span id="cosine"></span></p>
<p>Tangent: <span id="tangent"></span></p>
// Trigonometric Functions
document.getElementById("sine").innerText = Math.sin(Math.PI / 2);
document.getElementById("cosine").innerText = Math.cos(Math.PI);
document.getElementById("tangent").innerText = Math.tan(Math.PI / 4);
The Browser Object Model (BOM) represents the interaction between the browser and the window. It provides
objects and methods for controlling the browser, but it's not standardized, meaning its features may vary between
browsers. Common components of the BOM include the window, screen, document, and navigator objects.
<script>
window.alert("Hello, this is an alert!");
</script>
b) confirm() - Displays a dialog box with a specified message and OK/Cancel buttons.
<script>
let result = window.confirm("Do you want to proceed?");
if (result) {
document.write("User clicked OK.");
} else {
document.write("User clicked Cancel.");
}
</script>
c) prompt() - Displays a dialog box that prompts the user for input.
<script>
let userInput = window.prompt("Enter your name:");
document.write("User entered: " + userInput);
</script>
<script>
// Open a new window
window.open("https://www.google.com", "_blank");
</script>
The screen object represents the properties of the user's screen. Here are a couple of methods:
a) screen.width and screen.height - Retrieve the width and height of the user's screen.
<script>
document.write("Screen Width: " + screen.width);
document.write("Screen Height: " + screen.height);
</script>
b) screen.availWidth and screen.availHeight -Retrieve the available width and height of the user's
screen (excluding taskbars and other system elements).
<script>
document.write("Available Screen Width: " + screen.availWidth);
document.write("Available Screen Height: " + screen.availHeight);
</script>
15.iii).Accessing a geolocation
In JavaScript, you can use the Geolocation API to access the user's geographical location. The
Geolocation API provides a simple way to get the device's location (latitude and longitude).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Geolocation Example</title>
</head>
<body>
<h1>Geolocation</h1>
<p id="location"></p>
<script>
let loc = document.getElementById("location");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
loc.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;