css codes with output (1)
css codes with output (1)
<h1 id="myHeading">Hello!</h1>
<button onclick="document.getElementById('myHeading').innerText =
'Changed!';">Change Text</button>
</body>
</html>
(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;
</script>
</body>
</html>
3. navigator object code with its propeties and methods
<html><body>
<script>
let je = navigator.javaEnabled();
if(je){
document.write("Java is Enabled");
}
else document.write(" java not enabled ");
</script>
</body>
</html>
<html>
<body>
<script>
let obj = {
rollno:1,
name:"tejas",
get getRollnumber(){
return this.rollno;
},
set setName(newname){
return this.name=newname;
}
};
class Student{
constructor(rollno,name){
this.rollno = rollno;
this.name = name;
}
intro(){
return "Hello , Myself "+this.name+" & Roll Number "+this.rollno;
};
}
document.write(student2.intro()+"<br>");
document.write(student1.intro());
</script>
</body>
</html>
</script>
</body>
</html>
<html>
<body>
<script>
</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++){
// 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){
function OddEven(num){
if(num%2==0){
return true; // true means the number is even
}
else return false;
}
</script>
</body>
</html>
<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
// 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>");
}
// 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>");
}
</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>
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>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>
// 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
// 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
student["caste"]="bramhin";
document.write("Caste: "+student.caste + "<br>");
</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){
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();
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>
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;
</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>
(unit 2)
1. Write JavaScript to create an array called flowers with the names of 3 flowers and
display the elements.
<html>
<body>
<script>
<html>
<body>
<script>
let colors=["red","yellow","neon","blue"];
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
// 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>");
// 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>");
// Using for..of
const fruitsList = ['apple', 'banana', 'cherry'];
for (const fruit of fruitsList) {
document.write("for..of Fruit: " + fruit + "<br>");
}
// 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>");
</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);
}
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
// 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
// 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]
</script>
</body>
</html>
Unit 3
<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>
<!-- 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. -->
<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>
</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>
<br><br>
<br><br>
<br><br>
</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>
<div id="dropdowncontainer" > </div> // the dropdown list will be displayed through
inner html with respect to beverage selected
</form>
<script>
function checkboxchecked(checkbox){
dropdowncontainer.innerHTML="";
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;
}
</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)
<script>
// Function to append messages to the output area
function appendOutput(message) {
document.getElementById("output").innerHTML += message +
"<br>"; // Show messages
}
</body>
</html>
<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()">
<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>
<html>
<body>
<script>
document.getElementById("hoveroverme").addEventListener('mouseover',
function(){
alert("u hover over button hence mouseover is
triggered");
}
);
document.getElementById("ta").addEventListener('keypress',function()
{
document.getElementById("ta").addEventListener('keydown',function(){
alert("u presssed a NON-character key(ctrl or alt,etc)
so keydown was triggered");});
</script>
</body>
</html>
<html>
<body>
<script>
document.getElementById("hoveroverme").addEventListener('mouseover',
function(){
alert("u hover over button hence mouseover is triggered");
}
);
function tej(){
</body>
</html>
( 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>
<!DOCTYPE html>
<html>
<body>
<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!");
}
</body>
</html>
Child Objects of Window Object:
● history object
● Navigator object
● Screen object
● Location object
● Document object
A. 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();
<html>
<body>
<button onclick="goBack()">Back</button>
<button onclick="goForward()">Forward</button>
<script>
function showHistoryLength() {
function goBack() {
history.back();
function goForward() {
history.forward();
function goToPage() {
history.go(2);
</script>
</body>
</html>
B. Navigator Object
<html>
<body>
<h2>Navigator Object Example</h2>
<script>
function showAppName() {
function checkJavaEnabled() {
</script>
</body>
</html>
C. Screen Object
<!DOCTYPE html>
<html>
<body>
<script>
function showScreenWidth() {
alert("Screen Width: " + screen.width + " pixels");
function showScreenHeight() {
</script>
</body>
</html>
D. Location Object
<html>
<body>
<script>
function showLocationHref() {
function changeLocation() {
location.assign("https://www.openai.com");
}
// Location object: reload() method
function reloadPage() {
location.reload();
</script>
</body>
</html>
E. Document Object
Document Object Properties:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function showDocumentTitle() {
function writeToDocument() {
function createElementExample() {
document.body.appendChild(para);
</script>
</body>
</html>
( 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)
setAttribute(“attribute”,”value_of_attribute”);
● Code
<html>
<body>
<button id="btn">Button</button>
<script>
document.getElementById("btn").setAttribute("disabled",true);
</script>
</body>
</html>
Output:
( 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">
</select>
<script>
document.getElementById("vegi").value=2;
</script>
</body>
</html>
output:
● Code:
<html>
<body>
<label for="accept">
</label>
<script>
</script>
</body>
</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
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>
<br><br>
<script>
</script>
</body>
</html>
Output:
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">
</form>
<script>
newInput.setAttribute("type", "email");
</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
● Code:
<!DOCTYPE html>
<html>
<body>
<script>
</script>
</body>
</html>
Output:
Explanation:
( ata apan button click nahi karu shakat jaran apan button la disabled attribute dhila )
Code:
<html>
<body>
<button id="submitButton">Submit</button>
<script>
</script>
</body>
</html>
Output:
(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>
<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 )
● 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
❖ 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).
You should be using live server to work with cookies which u can get live server
extension in vs code
<html>
<body>
<script>
function createCookie(){
</script>
</body>
</html>
Output:
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 :
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>
<script>
function readCookie(){
// now all cookies name and value pair will be stored as array in
cookies like cookie[0] = username=atharv; etc
if(cookies[0]===""){
return;
}
}
</script>
</body>
</html>
<body>
<script>
function deleteCookie(){
</script>
</body>
</html>
(4.2- browser)
Syntax: window.open(URL, name, specs );
● 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”
<body>
<button id="btn" onclick="openNewWindow()"> Open New Window </button>
<script>
function openNewWindow(){
window.open("https://example.com","_blank");
</script>
</body>
</html>
<body>
<button id="btn" onclick="giveNewWindowFocus()"> Open & Give New Window
focus </button>
<script>
function giveNewWindowFocus(){
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>
<br><br>
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 –
<body>
<script>
function changeWholeContent() {
</script>
</body>
</html>
<html>
<body>
<script>
function changeElementContent() {
</script>
</body>
</html>
8. Closing a window
<body>
<br><br>
<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-
<html>
<body>
</div>
<script>
function scrollDown() {
function scrollDownBy() {
</script>
</body>
</html>
<body>
<script>
function open5window(){
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>
<script>
function webofNew() {
childWindow.document.write("<html><body><h1>This is
written via Parent Window</h1></body></html>");
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>
<script>
function webofNew() {
</script>
</body>
</html>
13. Javascript Security
14. Timers
● setTimeout()
<!DOCTYPE html>
<html>
<body>
<p id="message"></p>
<script>
function startTimer() {
setTimeout(function() {
}, 3000); // 3 seconds
</script>
</body>
</html>
● setInterval()
<html>
<body>
<script>
var count = 0;
var intervalId;
function startInterval() {
intervalId = setInterval(function() {
count++;
}, 1000); // 1 second
function stopInterval() {
clearInterval(intervalId);
</script>
</body>
</html>