Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
65 views

css codes with output (1)

Uploaded by

tejasnarwade2k5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

css codes with output (1)

Uploaded by

tejasnarwade2k5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 114

*Note:

* in exam if question says to display output on message box we will


use alert() to display result.eg: alert(“The addition is: “+res);
* try to think of simple methods to solve the question but with respect
to marks it holds

● document vapra jevha aplyala webpage varil content (jasa ki


text, images, kivabuttons) badalayecha asel.
Output: (after clicking n change text the text changed so this action took
place in webpage document so we use document when we want to change
content of webpage )
<!DOCTYPE html>
<html>
<body>

<h1 id="myHeading">Hello!</h1>
<button onclick="document.getElementById('myHeading').innerText =
'Changed!';">Change Text</button>

</body>
</html>

● window vapra jevha tumhala browser sobat kahi karayachay


asel (jasa ki alerts dakhavaycha, navi tabs open karaycha, kiva
window cha size ghenaycha).
<html>
<body>
<script>
window.alert("Hello!"); // Alert dakhavto
var name = window.prompt("Tumcha nav kay?"); // Input ghenato
var isSure = window.confirm("Tumhi sure aahat ka?"); // Confirmation
ghenato
</script>
</body>
</html>
Output: ( bagh he browser ne kelay alert cha so jevha pn browser shi kaam karvaicha
tevha window use karaicha)

(unit 1)

1. Write JavaScript to create an object "student" with properties roll number, name, branch,
year. Delete branch property and display remaining properties.

<html>
<body>
<script>

let student={

rollno:4,
name:"tejas",
branch:"co",
year:2
};

delete student.branch;
document.write("Student Details: <br>");
for(prop in student){
document.write(`${prop} : ${student[prop]} <br>`);
};

</script>
</body>
</html>

2. Write JavaScript to create a "person" object with properties firstname, lastname, age,
eye color; delete eye color property and display remaining properties

<html>
<body>
<script>
let person ={

firstname:"tejas",
lastname:"narwade",
age:19,
eyecolor:"blue"
};

delete person.eyecolor;

document.write("Properties of Person: <br> ");

for( prop in person){


document.write(prop + " : " + person[prop] + "<br>");

</script>
</body>
</html>
3. navigator object code with its propeties and methods

<html><body>
<script>

document.write("Browser name: " + navigator.appName + "<br>");


document.write("Browser Version: " + navigator.appVersion + "<br>");

let je = navigator.javaEnabled();

if(je){
document.write("Java is Enabled");
}
else document.write(" java not enabled ");

</script>
</body>
</html>

4. Accesor Properties(get() and set() ) code - Getter and setter

<html>
<body>
<script>
let obj = {
rollno:1,
name:"tejas",

get getRollnumber(){
return this.rollno;
},

set setName(newname){
return this.name=newname;
}
};

document.write(obj.getRollnumber + “<br>”); // calls getRollnumber and


display

obj.setName="tpokemon"; // set value for name in set property


document.write(obj.name); //displays updated name
</script>
</body>
</html>

5. Creating Objects Using the new Keyword in JavaScript


<html>
<body>
<script>

class Student{
constructor(rollno,name){
this.rollno = rollno;
this.name = name;
}

intro(){
return "Hello , Myself "+this.name+" & Roll Number "+this.rollno;
};
}

let student1 = new Student(1,"tejas");


let student2 = new Student(2,"atharv");

document.write(student2.intro()+"<br>");
document.write(student1.intro());

</script>
</body>
</html>

</script>
</body>
</html>

6. Write and explain the syntax of the prompt() method in JavaScript.

<html>
<body>
<script>

let name = prompt("Enter Your Name: ");

document.write("Your Name is "+name);

</script>
</body>
</html>
7. Write a JavaScript function to generate Fibonacci series till user-defined limit.

( The Fibonacci series is a sequence where each number is the sum of the two preceding ones.
This sequence starts with 0 and 1, and then each subsequent number is derived by adding the
two previous numbers. )

<html>
<body>
<script>

function fibo(limit){
series=[0,1];
for(let i = 2 ; i<=limit ; i++){

series.push( series[i-1] + series[i-2] );


}

return series.slice(0,limit); // to return series till the limit only


}

let limit = prompt("Enter the limit for Fibonaci seriess:");


document.write(fibo(Number(limit)));
</script>
</body>
</html>
8. Write a JavaScript program to check if the entered number is prime and even and odd

// remember to convert string input to number for eg. Number(num) this will convert string num
to Number

<html>
<body>
<script>

// if number gets divided by any number except 1 and itself then its not prime so we
here removed 1 and just check till half of that number so even its gets divided once its
not prime

function isPrime(num){

if (num <= 1){return false; }


for(let i = 2 ; i<=Math.sqrt(num) ; i++ ){
if (num%i == 0){
return false;
}
else return true;
}
}

function OddEven(num){

if(num%2==0){
return true; // true means the number is even
}
else return false;
}

let num = prompt("Enter Number: ");


document.write(" The number " + num + " is: ");
document.write(isPrime(Number(num)) ? "PRIME " : "NOT PRIME ");
document.write(OddEven(Number(num)) ? "Even" : "Odd" );

</script>
</body>
</html>

9. Code for all Operators in Javascript

<html>
<body>
<script>
// 1. Arithmetic Operators
document.write("<h3>Arithmetic Operators:</h3>");
document.write("5 + 2 = " + (5 + 2) + "<br>"); // Addition
document.write("5 - 2 = " + (5 - 2) + "<br>"); // Subtraction
document.write("5 * 2 = " + (5 * 2) + "<br>"); // Multiplication
document.write("5 / 2 = " + (5 / 2) + "<br>"); // Division
document.write("5 % 2 = " + (5 % 2) + "<br>"); // Modulus

let a = 5;
document.write("a++ = " + (a++) + "<br>"); // Increment (after print a becomes 6)
document.write("a-- = " + (a--) + "<br>"); // Decrement (after print a becomes 4)
document.write("Current value of a = " + a + "<br>");

// 2. Assignment Operators
document.write("<h3>Assignment Operators:</h3>");
let x = 5;
document.write("x = " + x + "<br>"); // Assignment
x += 5;
document.write("x += 5 = " + x + "<br>"); // Addition Assignment
x -= 5;
document.write("x -= 5 = " + x + "<br>"); // Subtraction Assignment
x *= 5;
document.write("x *= 5 = " + x + "<br>"); // Multiplication Assignment
x /= 5;
document.write("x /= 5 = " + x + "<br>"); // Division Assignment
x %= 5;
document.write("x %= 5 = " + x + "<br>"); // Modulus Assignment

// 3. Comparison Operators
document.write("<h3>Comparison Operators:</h3>");
document.write("5 == 5: " + (5 == 5) + "<br>"); // Equal to
document.write("5 === '5': " + (5 === '5') + "<br>"); // Strict equal (value and type)
document.write("5 != 3: " + (5 != 3) + "<br>"); // Not equal
document.write("5 !== '5': " + (5 !== '5') + "<br>"); // Strict not equal (value and type)
document.write("5 > 3: " + (5 > 3) + "<br>"); // Greater than
document.write("5 < 3: " + (5 < 3) + "<br>"); // Less than
document.write("5 >= 5: " + (5 >= 5) + "<br>"); // Greater than or equal to
document.write("5 <= 3: " + (5 <= 3) + "<br>"); // Less than or equal to

// 4. Logical Operators
document.write("<h3>Logical Operators:</h3>");
let y = 3;
document.write("x < 10 && y > 1: " + (x < 10 && y > 1) + "<br>"); // Logical AND
document.write("x == 5 || y == 5: " + (x == 5 || y == 5) + "<br>"); // Logical OR
document.write("!(x == y): " + !(x == y) + "<br>"); // Logical NOT

// 5. Bitwise Operators
document.write("<h3>Bitwise Operators:</h3>");
document.write("5 & 1 = " + (5 & 1) + "<br>"); // AND
document.write("5 | 1 = " + (5 | 1) + "<br>"); // OR
document.write("5 ^ 1 = " + (5 ^ 1) + "<br>"); // XOR
document.write("~5 = " + ~5 + "<br>"); // NOT
document.write("5 << 1 = " + (5 << 1) + "<br>"); // Left Shift
document.write("5 >> 1 = " + (5 >> 1) + "<br>"); // Right Shift
document.write("5 >>> 1 = " + (5 >>> 1) + "<br>"); // Unsigned Right Shift
// 6. String Operators
document.write("<h3>String Operators:</h3>");
document.write('"Hello" + " World" = ' + ("Hello" + " World") + "<br>"); //
Concatenation
let str1 = "Hello";
str1 += " World";
document.write("str1 += ' World' = " + str1 + "<br>"); // Concatenate Assignment

// 7. Conditional (Ternary) Operator


document.write("<h3>Conditional (Ternary) Operator:</h3>");
let condition = true;
document.write("condition ? 'Yes' : 'No' = " + (condition ? "Yes" : "No") + "<br>");

// 8. Type Operators
document.write("<h3>Type Operators:</h3>");
document.write("typeof 42 = " + typeof 42 + "<br>"); // Returns type of variable
let arr = [1, 2, 3];
document.write("arr instanceof Array = " + (arr instanceof Array) + "<br>"); // Checks
if arr is an instance of Array
</script>
</body>
</html>
10. Decision Making Statements code ( if,if else, if else if, nested if else , Switch case)
<html>
<body>
<script>

// 1. IF Statement
let age = 18;
document.write("IF Statement:<br>");
if (age >= 18) {
document.write("You are eligible to vote.<br>");
}

// 2. IF-ELSE Statement
let score = 45;
document.write("<br>IF-ELSE Statement:<br>");
if (score >= 50) {
document.write("You passed the exam.<br>");
} else {
document.write("You failed the exam.<br>");
}

// 3. NESTED IF-ELSE Statement


let num = -5;
document.write("<br>NESTED IF-ELSE Statement:<br>");
if (num > 0) {
document.write("The number is positive.<br>");
} else {
if (num === 0) {
document.write("The number is zero.<br>");
} else {
document.write("The number is negative.<br>");
}
}

// 4. IF-ELSE IF Statement
let marks = 82;
document.write("<br>IF-ELSE IF Statement:<br>");
if (marks >= 90) {
document.write("Grade: A<br>");
} else if (marks >= 75) {
document.write("Grade: B<br>");
} else if (marks >= 50) {
document.write("Grade: C<br>");
} else {
document.write("Grade: F<br>");
}

//5. Switch case


document.write("<h3> Switch case </h3>");

let day = Number(prompt("Enter Day from 1 to 7 any : "));


document.write("Today's week day name is : ");
switch (day){
case 1: document.write("Monday");break;
case 2: document.write("Tuesday");break;
case 3: document.write("wednesday");break;
case 4: document.write("thursday");break;
case 5: document.write("friday");break;
case 6: document.write("saturday");break;
case 7: document.write("sunday");break;
default: document.write("invalid day");
}

</script>
</body>
</html>
11. Looping statements code ( entry controlled - while, for..in, for + exit controlled - do
while,
/*
An entry-controlled loop checks the condition at the beginning of the loop (e.g., for, for..in,while),
so the loop may not execute if the condition is false initially.

An exit-controlled loop checks the condition at the end of the loop (e.g., do-while), ensuring the
loop runs at least once, regardless of the initial condition. */

<html>
<body>
<script>

// 1. Entry Controlled loop - for , for..in , while


document.write("<h4> 1 to 5 numbers using for loop </h4>");
for(let i = 0 ; i<=5 ; i++){
document.write(i);
}

document.write("<h4> Displaying properties of object using for..in loop ( for..in loop is speciaaly
used for looping through properties of object ): </h4>");
let tejas = {
name:"tejas",
age:19,
acad:"computer engg"
};

// now i will use for..in loop to display all properties of object tejas
for ( let prop in tejas){
document.write(prop +" : " + tejas[prop] + "<br>");
}

document.write("<h4>while loop to print 5's multiples: </h4> <br>");


let num = 1;
while(num<=10){
document.write((num*5) + "<br>");
num++;
}

// 2. Exit controlled loop - do while

document.write("<h4>displaying all even numbers till 10 using do while loop: </h4> <br>");
let n = 2;
do{
if(n%2==0){
document.write(n + "<br>");
}
n++;
}
while(n<=10)

</script>
</body>
</html>
12. Code demonstrating continue and break statements

/*
Continue statement: It is used to skip the rest of the code inside a loop for the current iteration
and move on to the next iteration of the loop.

Break statement: It is used to exit a loop or a switch statement prematurely. When the break
statement is encountered, it immediately terminates the loop or switch and transfers control to
the statement that follows the terminated statement
*/

<html>
<body>
<script>

// 1. Demonstration of keyword "continue" ( just skips current iteration whenever code discovers
the “continue” and the continue remaining iteration )

document.write("<h4> using continue keyword to skip the number 5 and display other remaining
numbers: </h4> <br>");
for ( let i = 0 ; i<= 10 ; i++){
if( i == 5 ){
continue;
}
document.write(i + "<br>");
}

// 2. Demonstration of keyword "break" ( we use break to exit the whole loop , its used in looping
statements and compulsorily in switch cases

document.write("<h4> using break keyword to break the loop if number 7 comes in iteration:
</h4> <br>");
for (let i = 0 ; i<50 ; i++){
if( i == 7 ){
break;
}
document.write(i + "<br>");
}

document.write("<h4> using break keyword to break the switch case if alphabet is matched in
switch(so that other should cases should not get executed if any of the case does) : </h4>
<br>");
let alphabet=prompt("Enter alphabet a-c : ");
switch (alphabet){
case "a": document.write("Apple");
break;
case "b": document.write("Ball");
break;
case "c": document.write("Cat");
break;
default: document.write("invalid alphabet ( a/b/c only )");
}

</script>
</body>
</html>
13. Code Demonstating Querying, Setting and deleting properties of JAVASCRIPt (dot
notation,bracket notation, Object.defineProperty(){},delete statement( delete
object.property_name)
<html>
<body>
<script>

document.write("<h4> 1. Querying Properties: </h4> <br>");


let student = {
name: "tejas",
age: 19,
fav_color: "purple"
};

// we can access values of properties of object vvia 2 ways * dot notation , *bracket
notation
// Using dot notation
document.write("Name:"+ student.name +"<br>"); // Output: tejas

// Using bracket notation for properties with special characters


document.write("Favorite Color:"+ student["fav_color"] +"<br>"); // Output: purple

document.write("<h4> 2. Setting Properties </h4> <br>");

// we can set / add new properties of object via 3 ways: dot notation,bracket notation,
Object.defineProperty(object,"prpoerty_name"){}
// Using dot notation to add a new property

student.course = "CO";
document.write("Course:"+ student.course + "<br>" ); // Output: CO

// Using bracket notation to add a new property dynamically

student["caste"]="bramhin";
document.write("Caste: "+student.caste + "<br>");

// Using Object.defineProperty for advanced settings


Object.defineProperty(student, "graduationYear", {
value: 2025,
writable: true,
enumerable: true,
configurable: true
});
document.write("Graduation Year:", student.graduationYear); // Output: 2025

document.write("<h4> 3. Deleting Properties </h4> <br>");


delete student.age; // Remove age property
document.write("Age after deletion:", student.age); // Output: undefined -- as i deleted
the "age" property of student

</script>
</body>
</html>

14. Write a JavaScript program to validate user accounts for multiple sets of user IDs and
passwords using switch case statement.

<html>
<body>
<script>
function auth(uid,pass){

switch (uid){

case "user1" : if (pass=== "pass1")


{ document.write(" Welcome User 1 <br>");}
else document.write("user 1 entered incorrect password<br>");
break;

case "user2" : if (pass === "pass2")


{ document.write(" Welcome user 2 <br>");}
else document.write("user 2 entered incorrect password<br>");
break;

case "user3" : if (pass === "pass3")


{ document.write(" Welcome user 3 <br>");}
else document.write("user 3 entered incorrect password<br>");
break;
default: document.write("Enter valid username");
}
}

let uid = prompt("Enter user id: ");


let pass = prompt("Enter password: ");

auth(uid,pass);

</script>
</body>
</html>
15. WAP to Check if Striing is a Palindrome or not (important question)

/*
This line str = str.replace(/[^a-z0-9]/gi, '').toLowerCase(); removes all non-
alphanumeric characters ([^a-z0-9]), converts str to lowercase, and prepares it for a case-
insensitive palindrome check.
*/

<html>
<body>
<script>
function isPali(str){
str = str.replace(/[^a-z0-9]/gi, '').toLowerCase();

if (str === str.split('').reverse().join('')){


document.write("String : " +str + " is a Palindrome <br> ");
}
else document.write("String : " +str + " is NOT a Palindrome <br> ");

let str = prompt("Enter a String: ");


isPali(str);
</script>
</body>
</html>

16. Code for Simple calculator using Switch statement

Remeber to convert string to number while doing arithmetic operations use “ Number() “ to
convert string to number or u can use parseInt

<html>
<body>
<script>

let num1 = Number(prompt("Enter Numbeer 1 : "));


let num2 = Number(prompt("Enter Number 2: "));
let op = prompt("Enter the Opertion (+,-,*,/,%) : ");

switch(op){

case "+" :
document.write("Addition is : " + (num1+num2) + "<br>");
break;

case "-" :
document.write("Subtraction is : " + (num1-num2) + "<br>");
break;

case "*" :
document.write("Multiplcation is : " + (num1*num2) + "<br>");
break;

case "/" :
document.write("Division is : " + (num1/num2) + "<br>");
break;

case "%" :
document.write("Modulo is : " + (num1%num2) + "<br>");
break;

default: document.write(" INvalid! (+,-,*,/,%) only !!");

</script>
</body>
</html>

17. Write a JavaScript that accepts a number and displays addition of digits of that number
in a message box.
Whenever its said to display result on message box use alert()
<html>
<body>
<script>

let num1 = Number(prompt("Enyter Number 1: "));


let num2 = Number(prompt("Enter number 2: "));
let result = num1+num2;
alert("Addition : " + result);
</script>
</body>
</html>

(unit 2)

1. Write JavaScript to create an array called flowers with the names of 3 flowers and
display the elements.
<html>
<body>
<script>

let flowers =["champa","rose","sunflower","marigold"];


for(let i=0 ; i<flowers.length ; i++){
document.write(flowers[i] + "<br>");
}
</script>
</body>
</html>
2. Write a JavaScript that initializes an array called Colours and displays the elements.

<html>
<body>
<script>

let colors=["red","yellow","neon","blue"];

for( i=0 ; i<colors.length ; i++){


document.write(colors[i] + "<br>");
}
</script>
</body>
</html>

Or

<html>
<body>
<script>

let colors=["red","yellow","neon","blue"];
document.write(colors);
</script>
</body>
</html>
3. Code for Demonstration of Array Constructor,methods

<html>
<body>
<script>
// 1) Ways to Construct an Array

// 1.1) JS array literal


var flowers = ["Rose", "Tulip", "Sunflower"];
document.write("Array Literal: " + flowers + "<br>");

// 1.2) Creating an instance of array directly


var fruits = new Array(); // declaration
fruits[0] = "Apple"; // initialization
fruits[1] = "Banana";
fruits[2] = "Cherry";
document.write("Instance of Array Directly: " + fruits + "<br>");

// 1.3) JS array constructor


var vegetables = new Array("Carrot", "Potato", "Tomato");
document.write("Array Constructor: " + vegetables + "<br>");

// 2) Common Array Methods

// 2.1) Array Creation and Initialization Methods


let array1 = new Array(5); // Creates an array of length 5
document.write("Array of Length 5: " + array1 + "<br>");

let arrayFromString = Array.from("hello"); // Creates an array from


a string
document.write("Array from String: " + arrayFromString + "<br>");

let arrayOfNumbers = Array.of(1, 2, 3); // Creates an array with


given elements
document.write("Array.of Example: " + arrayOfNumbers + "<br>");

// 2.2) Accessing and Modifying Elements


let arr = [1, 2, 3];
// Concat
let newArray = arr.concat([4, 5]);
document.write("After concat: " + newArray + "<br>");

// Push
newArray.push(6); // Adds 6 to the end
document.write("After push: " + newArray + "<br>");

// Pop
newArray.pop(); // Removes the last element
document.write("After pop: " + newArray + "<br>");

// Shift
newArray.shift(); // Removes the first element
document.write("After shift: " + newArray + "<br>");

// Unshift
newArray.unshift(0); // Adds 0 to the beginning
document.write("After unshift: " + newArray + "<br>");

// Slice → array. slice(start,end); extracts elements between


start and before end index
let slicedArray = newArray.slice(1, 3); // Extracts elements from
index 1 to 2
document.write("Slice from index 1 to 3: " + slicedArray + "<br>");

// Splice → is used to add or remove elements from array


newArray.splice(1, 0, 'a'); // at index 1 remove 0 element
and add ‘a’ at index 1
document.write("After splice: " + newArray + "<br>");

// 2.3) Searching and Sorting


// Finds the position of the first occurrence of 2, starting from
the beginning of the array
document.write("Index of 2: " + newArray.indexOf(2) + "<br>");

// Finds the position of the last occurrence of 2, starting from the


end of the array
document.write("Last Index of 2: " + newArray.lastIndexOf(2) +
"<br>");
// Finds element which is square of 2 i.e 4
let foundElement = newArray.find(element => element ==(2*2) );
document.write("Found Element Square of 2: " + foundElement +
"<br>");

let foundIndex = newArray.findIndex(element => element > 2); //


Finds index of first element > 2
document.write("Index of Element > 2: " + foundIndex + "<br>");

newArray.sort(); // Sorts the array


document.write("Sorted Array: " + newArray + "<br>");

newArray.reverse(); // Reverses the array


document.write("Reversed Array: " + newArray + "<br>");

// 2.4) Iteration Methods


newArray.forEach(element => document.write("forEach Element: " +
element + "<br>")); // Iterates and logs each element

// Every
document.write("All elements > 0: " + newArray.every(element =>
element > 0) + "<br>"); // Checks if all > 0

// Some
//Checks if any > 0
document.write("Any element > 0: " + newArray.some(element =>
element > 0) + "<br>");

// 2.5) Other Useful Methods


document.write("Joined Array: " + newArray.join(', ') + "<br>"); //
Joins elements into a string
document.write("Includes 2: " + newArray.includes(2) + "<br>"); //
Checks if 2 is in the array

// 3) Looping through an array


// Using forEach
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((number) => document.write("forEach Number: " +
number + "<br>"));

// Using for..of
const fruitsList = ['apple', 'banana', 'cherry'];
for (const fruit of fruitsList) {
document.write("for..of Fruit: " + fruit + "<br>");
}

// Using basic for loop


for (let i = 0; i < numbers.length; i++) {
document.write("Basic for Loop Number: " + numbers[i] + "<br>");
}

// Using while loop


let index = 0;
while (index < numbers.length) {
document.write("While Loop Number: " + numbers[index] + "<br>");
index++;
}

// 4) Merging Arrays
let arr1 = [1, 2, 3];
let arr2 = [3.7, 4.2, 5.9];
let arr3 = ["a", "b", "c"];
let mergedResult = arr1.concat(arr2, arr3);
document.write("Merged Arrays with '-': " + mergedResult.join("-") +
"<br>");

// 5) Associative arry ( nothing but same as object )


const values = {
CSS: 22519,
AJP: 22517,
OSY: 22516,
STE: 22518,
EST: 22447
};

for (let key in values) {


document.write(key + ": " + values[key] + "<br>"); // Displays
index and values
}

</script>
</body>
</html>
4. Code to demonstrate use of inbuilt functions such as parseInt & alert() , calling functions
via html using onload , FACTORIAL Recursion code
<html>
<body onload="wlcm()" unload="msg()">
<script>
function wlcm(){
document.write("<h4> WELCOME CALLED FROM HTML VIA ONLOAD </h4>");
}

function msg(){
alert("bye :( ");
}

// A factorial is a mathematical operation that multiplies a given positive integer by all the
positive integers less than it down to 1. i.e., 4! = 4x3x2x1

function factorial(n){
if(n <= 1) {
return 1; // as factorial of 0 or 1 is 1
}
return n * factorial(n - 1);
}

let n = parseInt(prompt("Enter number to find factorial: "));


let result = factorial(n);

alert(" The factorial of Number : " + n + " is " + result); // Added a space before 'is'

</script>
</body>
</html>
5. Code for demonstrating String constructors and methods

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript String Methods</title>
</head>
<body>
<script>
// Sample strings for demonstration
let str1 = "Hello"; // Double quoted
let str2 = 'World'; // Single quoted
let str3 = ` JavaScript is great! `; // Template literal

// 1. String Modifications
// .concat() - Combine two strings
let combined = str1.concat(", ", str2); // Combines str1 and str2
with a comma
document.write("Combined: " + combined + "<br>"); // Outputs:
Hello, World

// .repeat() - Repeat a string


let repeated = str1.repeat(3); // Repeats str1 three times
document.write("Repeated: " + repeated + "<br>"); // Outputs:
HelloHelloHello
// .replace() - Replace part of a string
let replaced = str3.replace("great", "awesome"); // Replaces
"great" with "awesome"
document.write("Replaced: " + replaced + "<br>"); // Outputs:
JavaScript is awesome!

// .replaceAll() - Replace all occurrences


let replaceAll = "banana, banana, banana".replaceAll("banana",
"apple"); // Replaces all bananas with apples
document.write("Replace All: " + replaceAll + "<br>"); // Outputs:
apple, apple, apple

// .slice() - Extract a part of a string


let sliced = str3.slice(2, 15); // Extracts characters from index
2 to 15
document.write("Sliced: " + sliced + "<br>"); // Outputs:
JavaScript is g

// .substring() - Extract between two indexes, syntax:


str3.substr(startIndex,EndIndex)
let substring = str3.substring(2, 15); // Extracts characters from
index 2 to 15
document.write("Substring: " + substring + "<br>"); // Outputs:
JavaScript is g

// .substr() - Deprecated, but still works syntax:


str3.substr(startIndex,length)
let substr = str3.substr(2, 10); // Extracts 10 characters
starting from index 2
document.write("Substr: " + substr + "<br>"); // Outputs:
JavaScript

// .toLowerCase() - Convert to lowercase


let lowerCase = str1.toLowerCase(); // Converts str1 to lowercase
document.write("Lowercase: " + lowerCase + "<br>"); // Outputs:
hello

// .toUpperCase() - Convert to uppercase


let upperCase = str2.toUpperCase(); // Converts str2 to uppercase
document.write("Uppercase: " + upperCase + "<br>"); // Outputs:
WORLD

// .trim() - Remove whitespace from both ends


let trimmed = str3.trim(); // Removes whitespace at the start and
end
document.write("Trimmed: '" + trimmed + "'<br>"); // Outputs:
'JavaScript is great!'

// .trimStart() - Remove whitespace from the start


let trimmedStart = str3.trimStart(); // Removes whitespace from
the start
document.write("Trimmed Start: '" + trimmedStart + "'<br>"); //
Outputs: 'JavaScript is great! '

// .trimEnd() - Remove whitespace from the end


let trimmedEnd = str3.trimEnd(); // Removes whitespace from the
end
document.write("Trimmed End: '" + trimmedEnd + "'<br>"); //
Outputs: ' JavaScript is great!'

// .padStart() - Pad the current string from the start


let paddedStart = str1.padStart(10, '*'); // Pads str1 with '*'
until it reaches length 10
document.write("Padded Start: '" + paddedStart + "'<br>"); //
Outputs: '****Hello'

// .padEnd() - Pad the current string from the end


let paddedEnd = str1.padEnd(10, '*'); // Pads str1 with '*' until
it reaches length 10
document.write("Padded End: '" + paddedEnd + "'<br>"); // Outputs:
'Hello****'

// 2. String Search & Match


// .indexOf() - Find the index of the first occurrence
let indexOfHello = combined.indexOf("Hello"); // Gets index of
"Hello"
document.write("Index of 'Hello': " + indexOfHello + "<br>"); //
Outputs: 0
// .lastIndexOf() - Find the index of the last occurrence
let lastIndexOfBanana = "banana, banana,
banana".lastIndexOf("banana"); // Gets index of last "banana"
document.write("Last Index of 'banana': " + lastIndexOfBanana +
"<br>"); // Outputs: 16

// .includes() - Check if string contains a value


let includesWorld = combined.includes("World"); // Checks if
combined contains "World"
document.write("Includes 'World': " + includesWorld + "<br>"); //
Outputs: true

// .startsWith() - Check if string starts with a value


let startsWithHello = combined.startsWith("Hello"); // Checks if
combined starts with "Hello"
document.write("Starts with 'Hello': " + startsWithHello +
"<br>"); // Outputs: true

// .endsWith() - Check if string ends with a value


let endsWithWorld = combined.endsWith("World"); // Checks if
combined ends with "World"
document.write("Ends with 'World': " + endsWithWorld + "<br>"); //
Outputs: true

// .match() - Match a string against a regex


let matches = str3.match(/Java/g); // Finds matches for "Java"
document.write("Matches: " + matches + "<br>"); // Outputs: Java

// .matchAll() - Get all matches including capturing groups


let allMatches = str3.matchAll(/(Java)/g); // Matches all
occurrences of "Java"
for (const match of allMatches) {
document.write("Match All: " + match[0] + "<br>"); // Outputs:
Java
}

// .search() - Search for a match in a string


let searchIndex = str3.search("great"); // Searches for "great"
document.write("Search for 'great': " + searchIndex + "<br>"); //
Outputs: 15
// 3. String Splitting & Joining
// .split() - Split a string into an array
let splitStr = "apple,banana,orange".split(","); // Splits by
comma
document.write("Split: " + splitStr + "<br>"); // Outputs:
apple,banana,orange

// .join() - Join array elements into a string


let joinedStr = splitStr.join(" - "); // Joins with " - "
document.write("Joined: " + joinedStr + "<br>"); // Outputs: apple
- banana - orange

// 4. String Extraction
// .charAt() - Get character at a specific index
let charAtExample = str1.charAt(1); // Gets character at index 1
document.write("Character at index 1: " + charAtExample + "<br>");
// Outputs: e

// .charCodeAt() - Get Unicode of character at an index


let charCodeExample = str1.charCodeAt(0); // Gets Unicode of
character at index 0
document.write("Unicode of character at index 0: " +
charCodeExample + "<br>"); // Outputs: 72

// .codePointAt() - Get Unicode code point value


let codePointExample = str1.codePointAt(0); // Gets code point at
index 0
document.write("Code Point at index 0: " + codePointExample +
"<br>"); // Outputs: 72

// .fromCharCode() - Create a string from Unicode values


let fromCharCodeExample = String.fromCharCode(72, 101, 108, 108,
111); // Creates a string from Unicode values
document.write("From Char Code: " + fromCharCodeExample + "<br>");
// Outputs: Hello

// .fromCodePoint() - Create a string from code points


let fromCodePointExample = String.fromCodePoint(72, 101, 108, 108,
111); // Creates a string from code points
document.write("From Code Point: " + fromCodePointExample +
"<br>"); // Outputs: Hello

// 5. String Conversion
// .toString() - Get string representation of an object
let obj = { name: "JavaScript" }; // An object
document.write("Object to String: " + obj.toString() + "<br>"); //
Outputs: [object Object]

// .valueOf() - Get the primitive value of a String object


let primitiveValue = new String("Hello").valueOf(); // Gets
primitive value
document.write("Value of String: " + primitiveValue + "<br>"); //
Outputs: Hello

</script>
</body>
</html>
Unit 3

1. CODE DEMONSTRATING ALL FORM ELEMENTS AND ATTRIBUTES


Note:
● <input> is a element and there are various attributes of input
elements →
1. type(button,text,list,checkbox,radio,email,password,etc)these were
values of attribute type
2 name
3 id
4 placeholder,etc
● <select> elements etc
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comprehensive HTML Form Example</title>
</head>
<body>
<!-- Form with all attributes and input elements -->
<form action="action.html" method="post" enctype="multipart/form-data"
target="_self" name="formExample" autocomplete="on" accept-charset="UTF-
8">

<h3> 1. Input element </h3>

<!-- Text Input type -->


<label for="username">Username:</label>
<input type="text" id="username" name="username"
placeholder="Enter your username" maxlength="10" minlength="3" required
autofocus><br><br>

<!-- Password Input type -->


<label for="password">Password:</label>
<input type="password" id="password" name="password"
required><br><br>
<!-- Button input type -->
<label for="button_as_input_type">Button Input: </label>
<input type="button" name="button_as_input_type" id="btn" >

<!-- Email Input type -->


<label for="email">Email:</label>
<input type="email" id="email" name="email"
autocomplete="off"><br><br>

<!-- Telephone Input type-->


<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{3}-[0-9]
{3}-[0-9]{4}" placeholder="123-456-7890"><br><br>

<!-- URL Input type -->


<label for="website">Website:</label>
<input type="url" id="website" name="website"
placeholder="https://example.com"><br><br>

<!-- Number Input type -->


<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="99"
step="1"><br><br>

<!-- Date Input type-->


<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob" min="1900-01-01" max="2023-
12-31"><br><br>

<!-- Range Input type-->


<label for="volume">Volume (0 to 100):</label>
<input type="range" id="volume" name="volume" min="0"
max="100"><br><br>

<!-- Color Input type -->


<label for="favcolor">Favorite Color:</label>
<input type="color" id="favcolor" name="favcolor"><br><br>

<!-- Radio Buttons type-->


<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br><br>

<!-- Checkbox type-->


<label>Subscribe to newsletter:</label>
<input type="checkbox" id="subscribe" name="subscribe"><br><br>

<!-- Submit and Reset Buttons type-->


<input type="submit" value="Submit">
<input type="reset" value="Reset"><br><br>

<!-- Hidden Input type -->


<input type="hidden" name="userID" value="12345">

<!-- File Input type-->


<label for="profilePic">Upload Profile Picture:</label>
<input type="file" id="profilePic" name="profilePic" accept=".jpg,
.jpeg, .png"> <br><br>

<!-- Image as Button type -->


<label>Submit with Image:</label>
<input type="image" src="path/to/image.jpg" alt="Submit
Image"><br><br>

<!-- Search Input type -->


<label for="search">Search:</label>
<input type="search" id="search" name="search"><br><br>

<h3> 2. textarea Element </h3>

<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="4" cols="50"
placeholder="Write something here..."></textarea><br><br>
<h3> 3. Button Element </h3>

<button type="button"><b> <i> Click Me </b> </i></button>

<h3> 4. select, option, and optgroup elements </h3>

<!-- The <select> element is used to create a drop-down list where users
can select one or more options.
Attributes:
- name: Used to reference it in form data (when submitted) and in
JavaScript.
- id: Unique identifier for targeting by CSS/JavaScript.
- multiple: Allows multiple selections if included.
- size: Specifies the number of visible options in the list.

<option> attributes:
- value: Value sent to the server when the form is submitted.
- selected: Pre-selects an option when the form loads.
- disabled: Makes the option unselectable.

<optgroup> attributes:
- label: Defines the group name displayed to users.
- disabled: Disables the entire group of options. -->

<label for="course">Select Course:</label>


<select name="course" id="course">
<optgroup label="Science">
<option value="biology">Biology</option>
<option value="chemistry">Chemistry</option>
</optgroup>
<optgroup label="Arts">
<option value="history">History</option>
<option value="philosophy">Philosophy</option>
</optgroup>
</select>
<h3> 5. The datalist element </h3>

<!-- <datalist> provides a list of pre-defined options for an <input>


element.
Unlike <select>, <datalist> suggests values without restricting
the input to the listed values. -->

<label for="browser">Select a Browser:</label>


<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>

<h3> 6. fieldset and legend elements </h3>


<!-- <fieldset> is used to group related elements within a form.
<legend> provides a caption or title for the group. -->

<fieldset>
<legend>Personal Information</legend>
<label for="name">Name:</label>
<input type="text" id="name" name="name">

<label for="age">Age:</label>
<input type="number" id="age" name="age">
</fieldset>

</form>
</body>
</html>

Output:
2. Write HTML code to design a form that displays two textboxes for accepting
two numbers, one textbox for accepting result and two buttons as ADDITION
and SUBTRACTION , MULTIPLICATION, DIVISION. Write proper JavaScript such that
when the user clicks
on any one of the button, respective operation will be performed on two
numbers and result will be displayed in result textbox.

<html>
<body>
<form>

<fieldset>

<label for="num1"> Enter Number 1: </label>


<input type="text" id="num1" name="num1" placeholder="10">

<label for="num2"> Enter Number 2: </label>


<input type="text" id="num2" name="num2" placeholder="5">

<label for="output"> Output: </label>


<input type="text" id="output" name="output">

</fieldset>

<div>
<button type="button" id="addn" name="addn" onclick="addf()"><b> ADD </b> </button>
<button type="button" id="subn" name="subn" onclick="subf()"> <b> SUBSTRACT </b>
</button>
<button type="button" id="muln" name="muln" onclick="mulf()"> <b> MULTIPLY </b>
</button>
<button type="button" id="divn" name="divn" onclick="divf()"> <b> DIVIDE </b>
</button>
</div>

</form>

<script>
function addf(){
let num1 = Number(document.getElementById("num1").value);
let num2 =Number( document.getElementById("num2").value);
document.getElementById("output").value=num1+num2;
}
function subf(){
let num1 = Number(document.getElementById("num1").value);
let num2 =Number( document.getElementById("num2").value);
document.getElementById("output").value=num1-num2;
}
function mulf(){
let num1 = Number(document.getElementById("num1").value);
let num2 =Number( document.getElementById("num2").value);
document.getElementById("output").value=num1*num2;
}
function divf(){
let num1 = Number(document.getElementById("num1").value);
let num2 =Number( document.getElementById("num2").value);
document.getElementById("output").value=num1/num2;
}

</script>
</body>
</html>

3. Write an HTML script that accepts Amount, Rate of Interest and Period from user. When
user submits the information a JavaScript function must calculate and display simple
interest in a message box. (Use formula S.I. = PNR/100)

<html>
<body>
<form>
<h3> <u> Simple Interest Calculator </u></h3>

<label for="amt"> Enter Amount : </label>


<input type="text" id="amt" name="amt" placeholder="2000">

<br><br>

<label for="roi"> Rate of Interest (%): </label>


<input type="text" id="roi" name="roi" placeholder="7">

<br><br>

<label for="period"> Period (In Years): </label>


<input type="text" id="period" name="period" placeholder="2">

<br><br>

<!-- submit is a predfined type of button which we can use directly-->


<input type="submit" value="submit" name="Submit" id="submit" onclick="calcSI()">

</form>

<script>

function calcSI(){
let p = Number(document.getElementById("amt").value);
let n = Number(document.getElementById("period").value);
let r = Number(document.getElementById("roi").value);

let si = p*n*r/100;
alert("Your Simple Interest is : " +si);
}

</script>
</body>
</html>
4.

<html>
<body>
<form>

<label for="bev">Select Beverages: </label>


<br>
<input type="checkbox" name="TEA" id="tea" value="tea" onclick="checkboxchecked(this)">
<label for="tea">TEA</label>
<br>
<input type="checkbox" name="coffee" id="coffee" value="coffee"
onclick="checkboxchecked(this)" >
<label for="coffee">COFFEE</label>
<br>
<input type="checkbox" name="softdrink" id="softdrink" value="softdrink"
onclick="checkboxchecked(this)">
<label for="softdrink">SOFT DRINK</label>
<br>

<div id="dropdowncontainer" > </div> // the dropdown list will be displayed through
inner html with respect to beverage selected

</form>

<script>

const dropdowncontainer = document.getElementById("dropdowncontainer");

function checkboxchecked(checkbox){

dropdowncontainer.innerHTML="";

if(checkbox.value=="tea" && checkbox.checked){


const teadropdown=
`<select id="teaselect">
<option>GREEN TEA</option>
<option> MILK TEA</option>
<option> Black TEA</option>
</select>`

dropdowncontainer.innerHTML += teadropdown;
}
else if(checkbox.value=="coffee" && checkbox.checked){
const coffeedropdown =
`<select id="coffeeselect">
<option>CAFFECINO</option>
<option>LATTE</option>
<option>EXPRESSO</option>
</select>`
dropdowncontainer.innerHTML += coffeedropdown;
}

else if(checkbox.value=="softdrink" && checkbox.checked){


const softdrinkdropdown=
`<select id="softdrinkselect">
<option>MAAZA</option>
<option>SPRITE</option>
<option>COCA-COLA</option>
</select>`
dropdowncontainer.innerHTML += softdrinkdropdown;
}
}

</script>

</body>
</html>

5. Code demonstrating All Mouse , key Events ( mostly the questions for events of
mouse,key were only for theory so need to prepare code, just understand and remember
the events and what happens when event is triiggered)

Very important table..just do this table only for mouse,key events


<!DOCTYPE html>
<html lang="en">
<body>

<h2>Mouse Events Example</h2>


<!-- Area to detect mouse actions -->
<div id="mouseArea"
onclick="handleClick()"
onmouseover="handleMouseOver()"
onmouseout="handleMouseOut()"
onmousedown="handleMouseDown()"
onmouseup="handleMouseUp()"
onmousemove="handleMouseMove(event)">
Hover or Click Here!
</div>

<!-- Area to display mouse event messages -->


<div id="output"></div>

<script>
// Function to append messages to the output area
function appendOutput(message) {
document.getElementById("output").innerHTML += message +
"<br>"; // Show messages
}

// Click event: Display when mouse is clicked


function handleClick() {
appendOutput('Mouse clicked!'); // Show click message
}

// Mouse over event: Display when mouse hovers


function handleMouseOver() {
appendOutput('Mouse is over the area!'); // Show hover message
}

// Mouse out event: Display when mouse leaves


function handleMouseOut() {
appendOutput('Mouse left the area!'); // Show leave message
}

// Mouse down event: Display when button is pressed


function handleMouseDown() {
appendOutput('Mouse button pressed down!'); // Show press
message
}

// Mouse up event: Display when button is released


function handleMouseUp() {
appendOutput('Mouse button released!'); // Show release
message
}

// Mouse move event: Display current position


function handleMouseMove(event) {
const x = event.clientX; // Get X coordinate
const y = event.clientY; // Get Y coordinate
appendOutput(`Mouse is moving at X: ${x}, Y: ${y}`); // Show
mouse position
}
</script>

</body>
</html>

● Key event code


<!DOCTYPE html>
<html lang="en">
<body>
<h2>Key Events Example</h2>
<!-- Input field to detect key actions -->
<input type="text" id="inputField"
onkeydown="handleKeyDown(event)" <!-- Trigger on key press
down -->
onkeyup="handleKeyUp(event)" <!-- Trigger on key release
-->
onkeypress="handleKeyPress(event)"> <!-- Trigger on character
key press -->
<p>Type something in the input box!</p>

<script>
function handleKeyDown(event) {
document.write('Key down: ' + event.key + '<br>'); // Show the
key pressed down
}

function handleKeyUp(event) {
document.write('Key up: ' + event.key + '<br>'); // Show the
key released
}

function handleKeyPress(event) {
document.write('Key pressed: ' + event.key + '<br>'); // Show
the character key pressed
}
</script>

</body>
</html>

● Other events code ( just see once before exam as onload and onunnload u know and
these 2 are only imp from other events)
<!DOCTYPE html>
<html lang="en">
<body onload="handleLoad()" onunload="handleUnload()">

<h2>Other Events Example</h2>


<!-- Form to demonstrate various events -->
<form onsubmit="handleSubmit(event)"> <!-- Trigger on form submission
-->
<label for="name">Name:</label>
<input type="text" id="name" name="name"
onfocus="handleFocus()" <!-- Trigger when input is focused
-->
onblur="handleBlur()"> <!-- Trigger when input loses
focus -->
<br><br>
<input type="submit" value="Submit">
</form>

<script>
function handleLoad() {
document.write('Page loaded!<br>'); // Show when the page is
fully loaded
}

function handleUnload() {
document.write('Page unloaded!<br>'); // Show when leaving the
page
}

function handleFocus() {
document.write('Input field focused!<br>'); // Show when input
is focused
}

function handleBlur() {
document.write('Input field blurred!<br>'); // Show when input
is blurred
}

function handleSubmit(event) {
event.preventDefault(); // Prevent default form submission
action
const name = document.getElementById('name').value; // Get
name value
document.write('Form submitted! Name: ' + name + '<br>'); //
Show submitted name
}
</script>

</body>
</html>

6. The code demonstrating use of EventListener

<html>
<body>

<button id="hoveroverme"> Hover here </button>


<textarea id="ta" rows="20" cols="25"> changge this
</textarea>

<script>

document.getElementById("hoveroverme").addEventListener('mouseover',
function(){
alert("u hover over button hence mouseover is
triggered");
}
);

document.getElementById("ta").addEventListener('keypress',function()
{

alert("u presssed a character key so keypress was


triggered");
}
);

document.getElementById("ta").addEventListener('keydown',function(){
alert("u presssed a NON-character key(ctrl or alt,etc)
so keydown was triggered");});

</script>

</body>
</html>

Keydown is triggered when any key is pressed (eg. “A” or “ctrl”)

Keypress when a character key is only pressed (eg. “A”)


OR we create a function to handle the event like here we created tej() to handle keypress
event

<html>
<body>

<button id="hoveroverme" > Hover here </button>


<textarea id="ta" rows="20" cols="25" onkeypress="tej()"> changge this
</textarea>

<script>

document.getElementById("hoveroverme").addEventListener('mouseover',
function(){
alert("u hover over button hence mouseover is triggered");
}
);

function tej(){

alert("key pressed an character key only");


}
</script>

</body>
</html>

7. Change the v=background color on basis of radio button selection

( remember when we want to just select one radio other should remain unselected we need to
give same value for name attribute inn all radio)

<html>
<body>

<form>

<label for="radioo">Select Option to Change background color of page


</label>
<br>

<input type="radio" id="r1" name="color"


onchange="document.body.style.backgroundColor='red'" > RED
<br>
<input type="radio" id="r2" name="color"
onchange="document.body.style.backgroundColor='green'"> GREEN
<br>
<input type="radio" id="r3" name="color"
onchange="document.body.style.backgroundColor='blue'"> BLUE
</form>
</body>
</html>
8. Code & Concept of Window Object and its child object: history object,navigator
object,screen object,location object,document object

Diagram to make the concept clear of Form objects:

● Code for Window Object Methods


The window object represents the browser window or browser tab. It gives access to browser
features, like showing alerts, opening new windows,etc
Note: Window is an object of the browser and not of JavaScript. JavaScript objects are string,
array, etc.

# Properties of Window Object


innerWidth: The width of the window’s content area (in pixels).
innerHeight: The height of the window’s content area (in pixels).
outerWidth: The outer width of the browser window, including toolbars and scrollbars.
outerHeight: The outer height of the browser window, including toolbars and scrollbars.
location: Provides the URL of the current page and allows redirecting to different pages.
document: Represents the HTML document loaded in the window.
history: Provides access to the browser's history, allowing navigation backward and forward.
navigator: Contains information about the browser, such as the user agent.
screen: Information about the user’s screen, like height, width, and color depth

# methods of Window Object


alert(message) - Displays an alert dialog with a message.
confirm(message) - Displays a dialog with an OK and Cancel button, returning true if OK is
clicked.
prompt(message, default) - Displays a dialog with a text input field, allowing the user to
enter a value.
open(url, target, features) - Opens a new browser window or tab.
close() - Closes the current window.

<!DOCTYPE html>
<html>
<body>

<h2>Window Object Methods Demo</h2>

<button onclick="showAlert()">Alert</button>
<button onclick="showConfirm()">Confirm</button>
<button onclick="showPrompt()">Prompt</button>
<button onclick="openNewWindow()">Open New Window</button>
<button onclick="closeNewWindow()">Close New Window</button>
<button onclick="useSetTimeout()">Set Timeout</button>
<script>
// 1. alert() → Shows a simple alert box
function showAlert() {
alert("This is an alert box!");
}

// 2. confirm() → Shows a confirm box with OK and Cancel


function showConfirm() {
confirm("Do you confirm?");
}

// 3. prompt() → Shows a prompt box for user input


function showPrompt() {
prompt("Enter your name:");
}

// 4. open() → Opens a new window (URL is optional)


let newWindow;
function openNewWindow() {
newWindow = window.open("https://www.example.com", "_blank");
}

// 5. close() → Closes the new window


function closeNewWindow() {
if (newWindow) newWindow.close();
}

// 6. setTimeout() → Runs code after a delay


function useSetTimeout() {
setTimeout(() => alert("This appears after 3 seconds!"), 3000);
}
</script>

</body>
</html>
Child Objects of Window Object:
● history object
● Navigator object
● Screen object
● Location object
● Document object

A. History Object

Properties and Methods of History Object :

● History Object Property: length - Returns the number of URLs in the history list.
● History Object Methods:
○ back() - Goes to the previous page in history. history.back();
○ forward() - Goes to the next page in history. history.forward();
○ go() - Loads a specific page in the history list, positive or negative values
navigate forward/backward. history.go();

History Object Code:

<html>

<body>

<h2>History Object Example</h2>

<!-- Buttons to test History object methods -->


<button onclick="showHistoryLength()">Show History Length</button>

<button onclick="goBack()">Back</button>

<button onclick="goForward()">Forward</button>

<button onclick="goToPage()">Go 2 Pages Forward</button>

<script>

// History object: length property

// Shows the number of URLs in history

function showHistoryLength() {

alert("History length: " + history.length);

// History object: back() method

// Goes back to the previous page in the history

function goBack() {

history.back();

// History object: forward() method

// Goes forward to the next page in the history

function goForward() {

history.forward();

// History object: go() method

// Goes forward by 2 pages

function goToPage() {
history.go(2);

</script>

</body>

</html>

B. Navigator Object

● Navigator Object Properties:


➢ appName - Returns the name of the browser.
➢ appVersion - Returns the version of the browser.
➢ appCodeName - Returns the code name of the browser.
➢ cookieEnabled - Returns true if cookies are enabled, false otherwise.
➢ userAgent - Returns the user-agent string of the browser.
➢ language - Returns the browser language.
➢ online - Returns true if the browser is online, false otherwise.

● Navigator Object Method:


○ javaEnabled() - Returns true if Java is enabled in the browser.
navigator.javaEnabled(); // true or false

Navigator object Code:

<html>

<body>
<h2>Navigator Object Example</h2>

<!-- Buttons to test Navigator object properties and methods -->

<button onclick="showAppName()">App Name</button>

<button onclick="checkJavaEnabled()">Is Java Enabled?</button>

<script>

// Navigator object: appName property

// Shows the browser's application name

function showAppName() {

alert("App Name: " + navigator.appName);

// Navigator object: javaEnabled() method

// Checks if Java is enabled in the browser

function checkJavaEnabled() {

alert("Java Enabled: " + navigator.javaEnabled());

</script>

</body>

</html>
C. Screen Object

Screen Object Properties:

● width - Returns the width of the screen in pixels.


● height - Returns the height of the screen in pixels.
● availWidth - Returns the available width of the screen.
● availHeight - Returns the available height of the screen.
● colorDepth - Returns the color depth of the screen.
● pixelDepth - Returns the pixel depth of the screen.

Screen Object Code:

<!DOCTYPE html>

<html>

<body>

<h2>Screen Object Example</h2>

<!-- Buttons to test Screen object properties -->

<button onclick="showScreenWidth()">Screen Width</button>

<button onclick="showScreenHeight()">Screen Height</button>

<script>

// Screen object: width property

// Shows the screen width of the user's device

function showScreenWidth() {
alert("Screen Width: " + screen.width + " pixels");

// Screen object: height property

// Shows the screen height of the user's device

function showScreenHeight() {

alert("Screen Height: " + screen.height + " pixels");

</script>

</body>

</html>

D. Location Object

Location Object Properties:

● href - Gets or sets the entire URL of the current page.


● protocol - Returns the protocol of the URL (e.g., "https:").
● hostname - Returns the domain name of the URL.
● port - Returns the port number of the URL.
● pathname - Returns the path of the URL.
● search - Returns the query string part of the URL.
● hash - Returns the anchor part of the URL.

Location Object Methods:

● assign(url) - Loads a new document at the specified URL.


● replace(url) - Replaces the current document with a new one, without saving in
history.
● reload() - Reloads the current page.
Location Object code:

<html>

<body>

<h2>Location Object Example</h2>

<!-- Buttons to test Location object properties and methods -->

<button onclick="showLocationHref()">Current URL</button>

<button onclick="changeLocation()">Go to OpenAI</button>

<button onclick="reloadPage()">Reload Page</button>

<script>

// Location object: href property

// Shows the current URL of the page

function showLocationHref() {

alert("Current URL: " + location.href);

// Location object: assign() method

// Redirects the user to a new URL

function changeLocation() {

location.assign("https://www.openai.com");

}
// Location object: reload() method

// Reloads the current page

function reloadPage() {

location.reload();

</script>

</body>

</html>

E. Document Object
Document Object Properties:

● url - Returns the URL of the current document.


● title - Gets or sets the title of the document.
● body - Returns the <body> element of the document.
● head - Returns the <head> element of the document.
● forms - Returns all the <form> elements in the document.
● links - Returns all the <a> elements in the document with an href attribute.
● images - Returns all the <img> elements in the document.

Document Object Methods:

● getElementById(id) - Returns an element by its ID.


● getElementsByClassName(className) - Returns all elements with the specified
class.
● getElementsByTagName(tagName) - Returns all elements with the specified tag
name.
● createElement(tagName) - Creates a new HTML element.
● write(content) - Writes directly to the document.
● writeln(content) - Writes to the document with a newline at the end.
Document Object Code:

<!DOCTYPE html>

<html>

<head>

<title>Document Object Example</title>

</head>

<body>

<h2>Document Object Example</h2>

<!-- Buttons to test Document object properties and methods -->

<button onclick="showDocumentTitle()">Show Title</button>

<button onclick="writeToDocument()">Write to Document</button>

<button onclick="createElementExample()">Add Paragraph</button>

<script>

// Document object: title property

// Shows the title of the document

function showDocumentTitle() {

alert("Document Title: " + document.title);

// Document object: write() method


// Writes text to the document

function writeToDocument() {

document.write("Hello, this is written by document.write()");

// Document object: createElement() method

// Adds a new paragraph element to the document

function createElementExample() {

let para = document.createElement("p");

para.innerHTML = "New paragraph added by createElement.";

document.body.appendChild(para);

</script>

</body>

</html>

8. Code + concept for Changing Attribute Value Dynamically


● Goal: Modify an element’s attribute using JavaScript, for example, to disable a button
and update its label text.
● Explanation:
○ setAttribute("disabled", true) applies the disabled attribute, making
the button unclickable.
○ innerHTML changes the content between the opening and closing <button>
tags, updating the text of button to Tejas Cah Button

( he bagh innerHTML ne apan jo open and closing element chya madhe text lihala asto kiva
html che attributes in this case button cha Name “Button” so apan .innerHTML use karun te
change karu shakto like from “Button” to “TEJAS CHA BUTTON” ani .setAttribute() ne element
che attribute set kiva update karu shakto)

Syntax of set Attribute:

setAttribute(“attribute”,”value_of_attribute”);

● Code

<html>

<body>

<button id="btn">Button</button>

<script>

document.getElementById("btn").setAttribute("disabled",true);

document.getElementById("btn").innerHTML="TEJAS CHA BUTTON";

</script>

</body>

</html>

Output:

9. Code + concept for Changing Option List Dynamically

● Goal: Select an option in a dropdown (select box) by changing its value


dynamically in JavaScript.
● Explanation:
○ By setting value to "2", JavaScript updates the select box to display the
option with value="2".
○ This method is commonly used when a selection depends on user actions
or other conditions.

( he bagh by default select element 1st option la display arto pn apan ithe
dynamically javascript ne select la value=”2” dhili so toh ata value 2 chya option
la display karnar jo ki cucumber ahe )

● Code
<html>

<body>

<select id="vegi">

<option value="1"> Brinjal </option>

<option value="2"> Cucumber </option>

</select>

<script>

document.getElementById("vegi").value=2;

</script>

</body>

</html>

output:

10. Code + Concept for Evaluating Checkbox Selection

● Goal: Check if a checkbox is checked and retrieve its state.


● Explanation:
○ querySelector("#accept") selects the checkbox element.
○ The .checked property checks if the checkbox is ticked (true if checked,
false otherwise).

( he bagh document.querySelector() same document.getElementById() sarkha


ahe faqt ekach difference ahe ki querySelector() ne apan element la by id or class
kashyane pan select karu shakto pan docuemnt.getElementById() madhe apan
faqt element chya “id” nech element la select karun shakto)

● Code:
<html>

<body>

<label for="accept">

<input type="checkbox" id="accept" name="accept"


value="yes">Accept

</label>

<script>

// Check if the checkbox is checked or not

const isChecked = document.querySelector("#accept").checked;

console.log(isChecked); // Logs true if checked, otherwise false

</script>

</body>

</html>

11. Code + Concept for Changing Label Dynamically

● Goal: Update the text inside a label element.


● Explanation:
○ The innerText property modifies only the visible text within the element,
updating it to "Updated Text".
○ innerText is useful for plain text updates as it ignores any embedded
HTML.

(mahitiye tu ata confused ashil innerHTML ani innerText madhe ,Donhi opening
and closing tags madhla content ch change kartat like: <label> he wla content
</label> so bagh innerHTML ne apan element cha sagla update karu shakto
include tags and text,etc but innerText ne faqt apan tya ELEMENT cha text
change karu shakto like label cha naav or button cha naav etc jari apan tyala
html tags dhile tari innerText tyala as a text ghenar jasa hya code madhe-
innerHTML use kela tejas to atharv karaila and tyat bold <b> tag use kela ani to
update pn zhala to athrv in bold “ATHARV” pn same bold tag apan innerText
madhe kela tar ttyane utkarsh to yuvraj text change kela and tyane “<b>
yuvraj </b>” la as a text update kela …samajla..u can see output

innerHTML: Sagla HTML content (tags, attributes, ani text) update


karta yeil. Here: tejas → ATHARV

innerText: Faqt text update karto, HTML tags na ignore karto and
tasacha tasa as a text update karto naki as a html tags , jasaki ithe
cod madhe: utkarsh → <b> yuvraj </b> )

● Code:
<html>

<body>

<label id="l1"> TEJAS </label>

<br><br>

<label id="l2"> utkarsh </label>

<script>

document.getElementById("l1").innerHTML="<b> ATHARV </b>";

document.getElementById("l2").innerText="<b> yuvraj <b> ";

</script>

</body>

</html>
Output:

12. Code + Concept Manipulating Form Elements

● Goal: Dynamically add a new input element to an existing form.


● Explanation:
○ createElement("input") creates a new input element.
○ setAttribute assigns attributes to the new input, making it an email
input with placeholder text.

Syntax of set Attribute:

setAttribute(“attribute”,”value_of_attribute”);

○ appendChild adds the new element to the form, updating the DOM
without reloading the page.
● Code:
<html>

<body>

<form id="myForm">

<input type="text" id="name" placeholder="Enter your name">

</form>

<script>

// Adding a new email input field to the form

const newInput = document.createElement("input");

newInput.setAttribute("type", "email");

newInput.setAttribute("placeholder", "Enter your email");


document.getElementById("myForm").appendChild(newInput);

</script>

</body>

</html>

13. Code + Concept for Intrinsic JS Functions (e.g., Custom Form Submit)

● Explanation:
○ Intrinsic Functions: Built-in functions provided by a programming
language that perform common tasks. They are optimized by the
language's compiler for efficient execution.
○ Example
○ In JavaScript, alert() is an intrinsic function that shows a popup
message.

Key Points

● Ready to Use: No need to define them yourself.


● Optimized: Fast execution due to compiler optimizations.

( intrinsic js function basically ase functions asatat jyacha workingg compiler la


pahilyapsun mahiit asta and user tyala directly use karu shaktat like alert(), prompt(),

● Code:
<!DOCTYPE html>

<html>

<body>

<button onclick="showMessage()">Click Me!</button>

<script>

// This is an intrinsic function that displays a message box


function showMessage() {

alert("Hello, World!"); // Displays a message when the


button is clicked

</script>

</body>

</html>

Output:

14. Code + Concept for Disabling Element

Goal: Disable a button to prevent user interaction.

Explanation:

○ disabled = true sets the button as disabled, making it inactive and


grayed out.
○ Useful in situations where you need to temporarily prevent actions until
specific conditions are met.

( ata apan button click nahi karu shakat jaran apan button la disabled attribute dhila )

Code:
<html>

<body>

<button id="submitButton">Submit</button>

<script>

// Disabling the button


document.getElementById("submitButton").disabled = true;

</script>

</body>

</html>

Output:

15.Code + Concept for Read-Only Elements

● Goal: Make a text input field read-only, preventing user edits.


● Explanation:
○ readOnly = true allows users to see the input but restricts editing.
○ Commonly used in forms where certain fields shouldn’t be changed by the
user.

(jasaki apan eka textbox chya la faqt readonly theu shakto so user faqt baghu
shako textbox madhe kahi text type nahi karu shakat)

● Code:

<html>

<body>

<input type="text" id="myInput" value="Read-Only Text ahe faqt


baghu shakto change nahi karu shakat">

<script>
// Setting the input field to read-only

document.getElementById("myInput").readOnly = true;

</script>

</body>

</html>

Output:

(unit 4) cookies and browser data (important chapter) cookies related code tula vvs code
madhech karava lagel and output sathi live server vs code extension use karava lagel

(4.1 - Cookies )

What are Cookies?

● Cookies are small pieces of data that websites store on a user’s computer through their
browser.
● They help remember user information, like login status or preferences, for future visits.
How Cookies Work

1. Storage: Websites create cookies to store data like login status, preferences, or items in
a cart.
2. Data Format: Cookies are stored as name=value pairs and may have additional
settings, like expiration.
3. Expiration: Cookies can be temporary (session cookies) or long-lasting (persistent
cookies).
4. Access: On future visits, the browser sends the cookie back to the website, allowing it to
"remember" the user.
5. Privacy: Cookies can track users across sites, raising privacy concerns.

Cookie Attributes

Note: expires date should not be of more than 6 month from now as some browser dont
allow cookie to remain in browser more than 1 or 2 year so follow following date only for
every question in exam

Eg: document.cookie = "username=atharv; path=/; expires=Fri, 25 Dec 2024 23:23:02


GMT; Secure; SameSite=Lax";

❖ Name=Value: Stores data as key-value pairsThe Name is the key used to identify the
cookie, and the Value is the data associated with that key.. username=atharv
❖ Path: Restricts cookie use to specific site areas. Mostly use this: path=/
❖ Expires/Max-Age: Sets how long the cookie lasts. Format: Wed, 25 Dec 2024 23:23:02
GMT
❖ Secure: Only sends the cookie over HTTPS.
❖ SameSite: Controls if cookies are sent with cross-site requests: mostly use
lax→ SameSite=LAX
● Lax: Sent on same-site and some cross-site requests.
● Strict: Sent only on same-site requests.
● None: Sent on all requests (must also be Secure).
❖ Domain: Limits cookie access to specific domains.
❖ HttpOnly: Blocks JavaScript from accessing the cookie (server-only).

Viewing Cookies in Browser

You should be using live server to work with cookies which u can get live server
extension in vs code

1. Right-click on the webpage and choose Inspect.


2. Navigate to Application > Cookies.
3. Select the URL under Cookies to see all cookies for that webpage.

1. Create / Write Cookie code + concept


Writing A Cookie / Creating a Cookie
document.cookie = "username=tejas; expires=Fri, 25 Dec 2024 23:23:02 GMT;
path=/; SameSite=Lax; Secure";

Use document.cookie=” “ to write/create a cookie and inside the double


quotes start with name attribute and other attributes like
path,expires,SameSite=Lax,Secure etc and each attribute should be
separated by semicolon
❖ Name=Value: Stores data as key-value pairs.
❖ Path: Restricts cookie use to specific site areas. Mostly use this: path=/
❖ Expires/Max-Age: Sets how long the cookie lasts. Format: Wed, 25 Dec 2024 23:23:02
GMT
❖ Secure: Only sends the cookie over HTTPS.
❖ SameSite: Controls if cookies are sent with cross-site requests: mostly use
lax→ SameSite=LAX
● Lax: Sent on same-site and some cross-site requests.

<html>

<body>

<button id="btn" onclick="createCookie()"> Create Cookie </button>

<script>

function createCookie(){

document.cookie="username=atharv ; path=\ ; expires= Wed, 25 Dec 2024


23:23:02 GMT ; SameSite=LAX ; Secure";

alert("Cookie Created Succesfully");

</script>

</body>

</html>
Output:

2. Read Cookie code + concept


See cookie store data in key and value i.e username=tejas , address=badlapur,
product=watch, etc mhanjech product is key and watch is value and the key and
value is used in future by browser until its expire date comes

How to read a Cookie?


For Reading a cookie, we will store all cookies in variable cookies by let cookies =
document.cookie.split("; ");

As we know cookies are stored in document with semicolon separating each cookie so
now we stored array of cookies in variable “cookies” and now we will check 0th index
if(cookies[0]===""){ document.write("No cookies found!"); return; }
jrr 0th index empty asel mhjech document madhe cookies nahit so
apan “cookies not found” asa sangnar and return use karnar function
chya baher padayla. Ani jrr cookies present astil tar apan for..of
loop lavnar :

for(let cookie1 of cookies){

let[name,value]=cookie1.split("=");
document.write("Cookie found: Cookie Name: "+name+" Cookie Value: "+value
+"<br>"); }}

Ithe “cookie1” cookies array madhllya index la represent karato so apan array madhyala
pratyek index madhe stored name and value la la store karnar “name” and “value”
variable madhe and mang tech display karanar .. pahila kiti simple ahe cookie read
karna .. (just confidence the swatah var and assume kar ki tula sagla mahit ahe karan
paper checker la pn limited knowledge ahe Javascript cha 🙂)

<html>

<body>

<button id="btn" onclick="readCookie()">Read Cookie</button>

<script>

function readCookie(){

// now all cookies name and value pair will be stored as array in
cookies like cookie[0] = username=atharv; etc

let cookies = document.cookie.split("; ");

if(cookies[0]===""){

document.write("No cookies found!"); // checks if cookies are


present or not

return;

for(let cookie1 of cookies){

let[name,value]=cookie1.split("="); // we separate name and value by


spliting name value pair by "="

document.write("Cookie found: Cookie Name: "+name+" Cookie Value:


"+value +"<br>");

}
}

</script>

</body>

</html>

3. Deleting a Cookie ( faqqt tyachi expiration date la change karaicha


kontya pan junya data shi like 01 Jan 1970,etc so browser automatic
delete karel cookie la karan browser la vata ki yachi expire date tr
houn geli tar lagech delete karava lagel cookie la and hence cookie
deleted! )
So aplyala cookie delete kariachay, so first of all jya pan cookie la delete
karaichay tya cookie cha exact name and value function madhe same
lihaycha and expiration date houn geleli date takaychi so browser la vata ki
yachi expire date tar houn geli so browser cookie la lagech delete karto ..
he bagh code samjel tula
<html>

<body>

<button id="btn" onclick="deleteCookie()"> Delete Cookie </button>

<script>

function deleteCookie(){

document.cookie="product=watch ; path=/ ; expires= Thu, 01 Jan 1970


00:00:00 GMT ; Secure ; SameSite=LAX ";

alert("Cookie deleted Succesfully");

</script>

</body>

</html>

(4.2- browser)
Syntax: window.open(URL, name, specs );

Example: window.open(“https://example.com”, “_blank”, “width=60 ,height=40,


left=100, top=100”);

● URL → any url u want or u can leave it blank “ “ or if want to specify url the
use https://example.com
● Name →

● Specs → “ width=100,height=100,left=100,top=100”

4. Code for Opening a New Window


The open() method opens a new browser window, or a new tab,

(when we create a new window it opens in another tab/window but we dont


redirect to that tab we need to manually click on newly created tab to go on
new tab )
<html>

<body>
<button id="btn" onclick="openNewWindow()"> Open New Window </button>

<script>

function openNewWindow(){

window.open("https://example.com","_blank");

</script>

</body>

</html>

5. Code for giving the new window focus


( when we use newWindow.focus() we automatically goes to that website
i.e newly created window comes in focus )
<html>

<body>
<button id="btn" onclick="giveNewWindowFocus()"> Open & Give New Window
focus </button>

<script>

function giveNewWindowFocus(){

let newWindow = window.open("https://example.com","_blank");

newWindow.focus(); //bring
new window to focus

</script>

</body>

</html>
6. Changing the window position
( When we create a window, we can set a specific position to the
new window. The attributes ‘left’ and ‘top’ are used to specify the
position of the new window. The volumes to these attributes are
passed in open() as parameters. )

We have only left and top attribute so we should use this left and op
attribute with maximum value to position window at bottom and right
respectively

<html>

<body>

<button id="btn1" onclick="windowPositionedAtTopLeft()"> New


window with position in top left </button>

<br><br>

<button id="btn2" onclick="windowPositionedAtBottomRight()"> New


window with position in bottom Right </button>
<script>

function windowPositionedAtTopLeft(){

window.open("https://example.com","_blank","width=60,height=40,left=
0,top=0");

function windowPositionedAtBottomRight(){

window.open("https://example.com","_blank","width=60,height=40,left=
2000,top=2000");

</script>

</body>

</html>
Output:
7. Changing the content of a window
The contents of a window can be changed dynamically in the
following ways –

- Changing the content of the whole window

To change the entire content of the window, you can use


document.write(), which replaces all existing content with new
HTML. This approach is typically used less often because it
completely overrides the current content.
<html>

<body>

<button onclick="changeWholeContent()">Change Entire Window


Content</button>

<script>

function changeWholeContent() {

// Replaces the entire content of the current window

document.write("<h1>This is the new content of the entire


window!</h1>");

</script>

</body>

</html>

- Changing the content of a specific element


To change the content of a specific element, you can target the
element by its ID and use .innerHTML to update its contents. This is
a more controlled approach and widely used for dynamically
updating parts of a page.
<!DOCTYPE html>

<html>

<body>

<h1 id="header">Original Header Content</h1>

<p id="paragraph">This is the original paragraph content.</p>

<button onclick="changeElementContent()">Change Element


Content</button>

<script>

function changeElementContent() {

// Change the content of specific elements using their IDs

document.getElementById("header").innerHTML = "Updated Header


Content!";

document.getElementById("paragraph").innerHTML = "This is the


updated paragraph content.";

</script>

</body>

</html>
8. Closing a window

The window.close() method closes the current window, or the window


on which it was called.
<html>

<body>

<button id="btn1" onclick="openWindow()"> oPEN window</button>

<br><br>

<button id="btn2" onclick="closeWindow()"> close window</button>

<script>

let newWindow;
function openWindow(){

newWindow = window.open("https://example.com","_blank");

function closeWindow(){

newWindow.close();

</script>

</body>

</html>

9. Scrolling a webpage
The contents of the document window can be scrolled to the specified
horizontal and vertical positions using-

● scrollTo() – It scrolls the document to the specified coordinates.

Syntax: window.scrollTo(x, y);


● scrollBy() – – The scrollBy() method scrolls the document by the
specified number of pixels.

Syntax: window.scrollBy(x, y);


<!DOCTYPE html>

<html>

<body>

<button onclick="scrollDown()">Scroll Down</button>

<button onclick="scrollDownBy()">Scroll Down By 100px</button>

<div style="height: 2000px;">

<!-- Extra content to enable scrolling -->

<p>Scroll down to see more content here...</p>

</div>

<script>

function scrollDown() {

// Scroll to a specific position (x, y) on the page

window.scrollTo(0, 500); // Scrolls to 500 pixels from the top

function scrollDownBy() {

// Scroll down by a certain amount

window.scrollBy(0, 100); // Scrolls down by 100 pixels from


current position

</script>

</body>
</html>

10. Opening multiple windows in single click


<html>

<body>

<button id="btn1" onclick="open5window()"> Open 5 window in one


Click</button>

<script>

function open5window(){

for(let i=0 ; i<5 ; i++){

window.open("","","width=60,height=60");

</script>

</body>

</html>
11. Creating a web page in new window

We can write content to newly created windows once they are created
either using the standard document.write() method or potentially even
manipulate the window with DOM methods. The HTML code as string
parameter passed to the write function.
<!DOCTYPE html>
<html>

<body>

<button id="btn1" onclick="webofNew()">Click to create a child


window and write HTML via this Parent Window</button>

<script>

function webofNew() {

// Open a new window

let childWindow = window.open("", "",


"width=600,height=600");

// Write HTML content to the child window

childWindow.document.write("<html><body><h1>This is
written via Parent Window</h1></body></html>");

// Close the document to ensure the content is


rendered

childWindow.document.close();

</script>

</body>

</html>
12. Javascript in url
javascript: pseudo-protocol, which allows you to execute JavaScript
code directly in the URL field of a web browser.
<!DOCTYPE html>

<html>

<body>

<button id="btn1" onclick="webofNew()">javascript in url </button>

<script>

function webofNew() {

let childWindow = window.open("javascript:alert('this code


is written in url')", "", "width=600,height=600");

</script>

</body>

</html>
13. Javascript Security

( just remember these common vulnerabilities and protective measures)

Vulnerability: JavaScript code is accessible to users, making it easier for


attackers to find and exploit weaknesses.

1. Exploitation: Attackers can modify code in their browsers or send


harmful requests to servers, bypassing front-end protections.
2. Protection Measures:
○ Sandboxing: Run scripts separately, limiting their access to
resources.
○ Same Origin Policy: Prevent scripts from one site from
accessing data from another site.
3. Common Vulnerabilities:
○ Cross-Site Scripting (XSS): Attackers inject malicious code into
web applications, which runs in users' browsers, capturing
sensitive information or cookies.
○ Cross-Site Request Forgery (CSRF): Attackers trick users into
performing actions on a site where they are authenticated,
potentially changing passwords or making unauthorized
transactions.

14. Timers

In JavaScript, a timer is created to execute a task or any function at a


particular time.

Basically, the timer is used to delay the execution of the program or to


execute the JavaScript code in a regular time interval.

● setTimeout()
<!DOCTYPE html>

<html>

<body>

<button onclick="startTimer()">Start Timer</button>

<p id="message"></p>

<script>

function startTimer() {
setTimeout(function() {

document.getElementById("message").innerText = "Time's up!";

}, 3000); // 3 seconds

</script>

</body>

</html>

● setInterval()
<html>

<body>

<button onclick="startInterval()">Start Counting</button>

<button onclick="stopInterval()">Stop Counting</button>

<p id="count">Count: 0</p>

<script>

var count = 0;
var intervalId;

function startInterval() {

intervalId = setInterval(function() {

count++;

document.getElementById("count").innerText = "Count: " + count;

}, 1000); // 1 second

function stopInterval() {

clearInterval(intervalId);

</script>

</body>

</html>

You might also like