<script type="text/javascript"> //JS code goes here </script>
<script src="filename.js"></script>
<script>
//Single Line Comment
</script>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
Note : Changing the innerHTML property of an HTML element is a common way to display data in HTML. <p>Never call document.write after the document has finished loading.It will overwrite the whole document.</p>
<script>
document.write(5 + 6);
</script>
Note : Using document.write() after an HTML document is loaded, will delete all existing HTML: <h2>alert</h2>
<p>My first alert message.</p>
<script>
window.alert(5 + 6);
</script>
Note : You can skip the window keyword. <h2>Activate Debugging</h2>
<p>F12 on your keyboard will activate debugging.</p>
<p>Then select "Console" in the debugger menu.</p>
<p>Then click Run again.</p>
<script>
console.log(5 + 6);
</script>
Note : For debugging purposes, you can call the console.log() method in the browser to display data. <h2>The window.print() Method</h2>
<p>Click the button to print the current page.</p>
<button onclick="window.print()">Print this page</button>
Note : JavaScript does not have any print object or print methods. <p id="demo"></p>
<script>
x = 5;
y = 6;
z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
Note :- It's a good programming practice to declare all variables at the beginning of a script. <p id="demo"></p>
<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
Note :- The var keyword was used in all JavaScript code from 1995 to 2015. <p id="demo"></p>
<script>
let x = 5;
let y = 6;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
<p id="demo"></p>
<script>
const x = 5;
const y = 6;
const z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>
Note :- When to use JavaScript const? <script>
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
</script>
<p id="demo"></p>
<script>
let carName1 = "Volvo XC60";
let carName2 = 'Volvo XC90';
let answer1 = "It's alright";
document.getElementById("demo").innerHTML =
carName1 + "<br>" +
carName2 + "<br>" +
answer1;
</script>
Note :- When adding a number and a string, JavaScript will treat the number as a string. <p id="demo"></p>
<script>
let x1 = 34.00;
let x2 = 34;
let x3 = 3.14;
document.getElementById("demo").innerHTML =
x1 + "<br>" + x2 + "<br>" + x3;
</script>
Note :- Most programming languages have many number types: <p id="demo"></p>
<p>You cannot perform math between a BigInt type and a Number type.</p>
<script>
let x = BigInt("123456789012345678901234567890");
document.getElementById("demo").innerHTML = x;
</script>
<p id="demo"></p>
<script>
let x = 5;
let y = 5;
let z = 6;
document.getElementById("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>
Note :- Booleans are often used in conditional testing. <p id="demo"></p>
<script>
let car = "Volvo";
car = undefined;
document.getElementById("demo").innerHTML = car + "<br>" + typeof car;
</script>
<h1>JavaScript Functions</h1>
<p>Call a function which performs a calculation and returns the result:</p>
<p id="demo"></p>
<script>
function myFunction(p1, p2) {
return p1 * p2;
}
let result = myFunction(4, 3);
document.getElementById("demo").innerHTML = result;
</script>
<p id="demo"></p>
<script>
let hello = "";
hello = () => {
return "Hello World!";
}
document.getElementById("demo").innerHTML = hello();
</script>
if (condition) {
// block of code to be executed if the condition is true
}
Note :- if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error. <p id="demo">Good Evening!</p>
<script>
let x = 2;
if (x < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:
<p id="demo"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
greeting = "Good day!!!!";
} else {
greeting = "Good evening!!!!";
}
document.getElementById("demo").innerHTML = greeting;
</script>
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example:
<p id="demo"></p>
<script>
const time = new Date().getHours();
let greeting;
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
document.getElementById("demo").innerHTML = greeting;
</script>
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default:
// code block
}
Example:
<p id="demo"></p>
<script>
let day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.getElementById("demo").innerHTML = "Today is " + day;
</script>
for (initialization; condition; updation) {
// code block to be executed
}
Example :
for (let i = 0; i < 5; i++) {
text += "Iteration number: " + i + "
";
}
while (condition) {
// code block to be executed
}
Example :
<p id="demo"></p>
<script>
let text = "";
let i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}
document.getElementById("demo").innerHTML = text;
</script>
do {
// run this code in block
i++;
} while (condition);
Example :
<p id="demo"></p>
<script>
let text = ""
let i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 9);
document.getElementById("demo").innerHTML = text;
</script>
str.length()
Example
<p>The length of the string is:</p>
<p id="demo"></p>
<script>
let text = "Kaushal Jacker";
document.getElementById("demo").innerHTML = text.length;
</script>
Note :- JavaScript counts positions from zero. str.toUpperCase()
Example
<button onclick="myFunction()">Try it</button>
<p id="demo">SpecBits!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.toUpperCase();
}
</script>
str.toLowerCase()
Example
<button onclick="myFunction()">Try it</button>
<p id="demo">SpecBits!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.toLowerCase();
}
</script>
str.charAt(3)
Example
<p>The charAt() method returns the character at a given position in a string:</p>
<p id="demo"></p>
<script>
var text = "Kaushal Jacker";
document.getElementById("demo").innerHTML = text.charAt(2);
</script>
str1.concat(str2)
Example
<p id="demo"></p>
<script>
let text1 = "Hello";
let text2 = "World!";
let text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>
Note :- The concat() method can be used instead of the plus operator. str.slice(0,5)
Example
<script>
let text = "Apple, Banana, Kiwi";
let part = text.slice(7,13);
document.getElementById("demo").innerHTML = part;
</script>
str.substring(0,5)
Example
<p id="demo"></p>
<script>
let str = "Apple, Orange, Kiwi";
document.getElementById("demo").innerHTML = str.substring(7,13);
</script>
Note :- If you omit the second parameter, substring() will slice out the rest of the string. str.substr(2,5)
Example
<p id="demo"></p>
<script>
let str = "Apple, Pineapple, Kiwi";
document.getElementById("demo").innerHTML = str.substr(7,6);
</script>
Note :- If you omit the second parameter, substr() will slice out the rest of the string. string.replace(searchValue, newValue)
Example
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit SpecBits and SpecBits!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace("SpecBits","Developersarmy");
}
</script>
<button onclick="myFunction()">Try it</button>
<p id="demo">Please visit SpecBits!</p>
<script>
function myFunction() {
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML =
text.replace(/SPECBITS/i,"Developersarmy");
}
</script>
Note :-
The replace() method does not change the string it is called on. string.replaceAll(searchValue, newValue)
Example
<p id="demo"></p>
<script>
let text = "I love cats. Cats are very easy to love. Cats are very popular."
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");
document.getElementById("demo").innerHTML = text;
</script>
Note :-
replaceAll() is an ES2021 feature. string.trim()
Example
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trim();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
string.trimStart()
Example
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trimStart();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
string.trimEnd()
Example
<p id="demo"></p>
<script>
let text1 = " Hello World! ";
let text2 = text1.trimEnd();
document.getElementById("demo").innerHTML =
"Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
</script>
string.split(separator, limit)
Note :- separator & limit are Optional. Example
<p id="demo"></p>
<script>
let text = "a,b,c,d,e,f";
const myArray = text.split(",");
document.getElementById("demo").innerHTML = myArray[4];
</script>
Note : If the separator is omitted, the returned array will contain the whole string in index [0]. string.indexOf(searchvalue, start)
Note :- start is optional Example
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>
<script>
let text = "Please locate where 'locate' occurs!";
let index = text.indexOf("locate");
document.getElementById("demo").innerHTML = index;
</script>
string.lastIndexOf(searchvalue, start)
Note :- start is optional Example
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>
<script>
let text = "Please locate where 'locate' occurs!";
let index = text.lastIndexOf("locate");
document.getElementById("demo").innerHTML = index;
</script>
string.search(searchValue)
Example
<p>The position of the first occurrence of "locate" is:</p>
<p id="demo"></p>
<script>
let text = "Please locate where 'locate' occurs!";
let index = text.search("locate");
document.getElementById("demo").innerHTML = index;
</script>
Note :- The search() method cannot take a second start position argument. string.match(match)
Example
<p>Perform a global, case-insensitive search for "ain":</p>
<p id="demo"></p>
<script>
let text = "The rain in SPAIN stays mainly in the plain";
const myArr = text.match(/ain/gi);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>
Note :- If a regular expression does not include the g modifier (global search), match() will return only the first match in the string. string.matchAll(match)
Example
<p>Perform a global, case-insensitive search for "ain":</p>
<p id="demo"></p>
<script>
let text = "The rain in SPAIN stays mainly in the plain";
const myArr = text.matchAll(/ain/gi);
document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
</script>
Note :- matchAll() is an ES2020 feature. string.includes(searchvalue, start)
Note :- start is optional. Example
<p>Check if a string includes "world":</p>
<p id="demo"></p>
<p>The includes() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.includes("world");
</script>
Note :- includes() is case sensitive. string.includes(searchvalue, start)
Note :- start is optional. Example
<p id="demo"></p>
<p>The startsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world", 6);
</script>
Note :- startsWith() is case sensitive. string.endsWith(searchvalue, length)
Note :- length is optional. Example
<p id="demo"></p>
<p>The startsWith() method is not supported in Internet Explorer.</p>
<script>
let text = "Hello world, welcome to the universe.";
document.getElementById("demo").innerHTML = text.startsWith("world", 6);
</script>
Note :- endsWith() is case sensitive. const array_name = [item1, item2, ...];
const cars = new Array("Saab", "Volvo", "BMW");
Note :- It is a common practice to declare arrays with the const keyword. <p id="demo"></p>
<script>
const cars = [
"Saab",
"Volvo",
"BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>
<p id="demo"></p>
<script>
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
document.getElementById("demo").innerHTML = cars;
</script>
<p id="demo"></p>
<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars[0];
</script>
Note :- Array indexes start with 0. array.toString()
Note :- All JavaScript objects have a toString() method. Example
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
<p id="demo"></p>
<script>
const person = {firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML = person.firstName;
</script>
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let size = fruits.length;
document.getElementById("demo").innerHTML = size;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.pop();
document.getElementById("demo2").innerHTML = fruits;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const example = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = example.pop();
document.getElementById("demo2").innerHTML = example;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.push("Kiwi");
document.getElementById("demo2").innerHTML = fruits;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const example = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = example.push("Kiwi");
document.getElementById("demo2").innerHTML = example;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.shift();
document.getElementById("demo2").innerHTML = fruits;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const example = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = example.shift();
document.getElementById("demo2").innerHTML = example;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.unshift("Lemon");
document.getElementById("demo2").innerHTML = fruits;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const example = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = example.unshift("Lemon");
document.getElementById("demo2").innerHTML = example;
</script>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML =
"The first fruit is: " + fruits[0];
delete fruits[0];
document.getElementById("demo2").innerHTML =
"The first fruit is: " + fruits[0];
</script>
<p id="demo"></p>
<script>
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = myGirls.concat(myBoys);
document.getElementById("demo").innerHTML = myChildren;
</script>
Note :- The concat() method does not change the existing arrays. It always returns a new array.<p id="demo"></p>
<script>
const array1 = ["Cecilie", "Lone"];
const array2 = ["Emil", "Tobias", "Linus"];
const array3 = ["Robin", "Morgan"];
const result = array1.concat(array2, array3);
document.getElementById("demo").innerHTML = result;
</script>
Note :- The concat() method can also take strings as arguments: <p id="demo"></p>
<script>
const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
document.getElementById("demo").innerHTML = newArr;
</script>
Note :- JavaScript Array flat() is supported in all modern browsers since January 2020: array.splice(index, howmany, item1, ....., itemX)
howmany, item1, ....., itemX are optional <p id="demo1"></p>
<p id="demo2"></p>
<p id="demo3"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;
let removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed;
</script>
Note :- The splice() method returns an array with the deleted items: array.splice(0, 1);
array.slice(start, end)
start & end are optional <p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = fruits.slice(1);
document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
</script>
Note :- The slice() method creates a new array. array.sort();
array.sort();
array.reverse();
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo1").innerHTML = points;
points.sort(function(a, b){return a - b});
document.getElementById("demo2").innerHTML = points;
</script>
<button onclick="myFunction()">Click multiple times</button>
<p id="demo"></p>
<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(){return 0.5 - Math.random()});
document.getElementById("demo").innerHTML = points;
}
</script>
<p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value, index, array) {
txt += value + "<br>";
}
</script>
Note :- When a callback function uses only the value parameter, the index and array parameters can be omitted: <p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value, index, array) {
txt += value + "<br>";
}
</script>
Note :- When a callback function uses only the value parameter, the index and array parameters can be omitted: <p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
const over18 = numbers.filter(myFunction);
document.getElementById("demo").innerHTML = over18;
function myFunction(value) {
return value > 18;
}
</script>
reduce() method The reduce() method runs a function on each array element to produce (reduce it to) a single value. <p id="demo"></p>
<script>
const numbers = [45, 4, 9, 16, 25];
let sum = numbers.reduce(myFunction);
document.getElementById("demo").innerHTML = "The sum is " + sum;
function myFunction(total, value, index, array) {
return total + value;
}
</script>
array.indexOf(item, start)
start is optional. <p id="demo"></p>
<script>
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
document.getElementById("demo").innerHTML = "Apple is found in position " + position;
</script>
Note :- Array.indexOf() returns -1 if the item is not found. array.find(function(currentValue, index, arr),thisValue)
index is optional. <p id="demo"></p>
<script>
const numbers = [4, 9, 16, 25, 29];
let first = numbers.find(myFunction);
document.getElementById("demo").innerHTML = "First number over 18 is " + first;
function myFunction(value, index, array) {
return value > 18;
}
</script>
Note :- The findIndex() method returns the index of the first array element that passes a test function. Array.from(object, mapFunction, thisValue)
mapFunction is optional. <p id="demo"></p>
<script>
const myArr = Array.from("ABCDEFG");
document.getElementById("demo").innerHTML = myArr;
</script>
Note :- from() is not supported in Internet Explorer.<p id="demo"></p>
<script>
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const q3 = ["Jul", "Aug", "Sep"];
const q4 = ["Oct", "Nov", "May"];
const year = [...q1, ...q2, ...q3, ...q4];
document.getElementById("demo").innerHTML = year;
</script>
Note :- ... is not supported in Internet Explorer.<p id="demo"></p>
<script>
let x = 123;
document.getElementById("demo").innerHTML =
x.toString() + "<br>" +
(123).toString() + "<br>" +
(100 + 23).toString();
</script>
<p id="demo"></p>
<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
x.toExponential() + "<br>" +
x.toExponential(2) + "<br>" +
x.toExponential(4) + "<br>" +
x.toExponential(6);
</script>
Note :- The parameter is optional. If you don't specify it, JavaScript will not round the number. <p id="demo"></p>
<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
x.toFixed(0) + "<br>" +
x.toFixed(2) + "<br>" +
x.toFixed(4) + "<br>" +
x.toFixed(6);
</script>
Note :- toFixed(2) is perfect for working with money.<p id="demo"></p>
<script>
let x = 9.656;
document.getElementById("demo").innerHTML =
x.toPrecision() + "<br>" +
x.toPrecision(2) + "<br>" +
x.toPrecision(4) + "<br>" +
x.toPrecision(6);
</script>
<p id="demo"></p>
<script>
let x = 123;
document.getElementById("demo").innerHTML =
x.valueOf() + "<br>" +
(123).valueOf() + "<br>" +
(100 + 23).valueOf();
</script>
Note :- In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object). <p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
Number(true) + "<br>" +
Number(false) + "<br>" +
Number("10") + "<br>" +
Number(" 10") + "<br>" +
Number("10 ") + "<br>" +
Number(" 10 ") + "<br>" +
Number("10.33") + "<br>" +
Number("10,33") + "<br>" +
Number("10 33") + "<br>" +
Number("John");
</script>
Note :- If the number cannot be converted, NaN (Not a Number) is returned. <p id="demo"></p>
<script>
let x = new Date("1970-01-01");
document.getElementById("demo").innerHTML = Number(x);
</script>
Note :- The Date() method returns the number of milliseconds since 1.1.1970. <p id="demo"></p>
<script>
let x = new Date("1970-01-02");
document.getElementById("demo").innerHTML = Number(x);
</script>
<p id="demo"></p>
<script>
const d = new Date("2022-03-25");
document.getElementById("demo").innerHTML = d;
</script>
Note :- Date objects are static. The "clock" is not "running". <p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.PI;
</script>
Note :- Unlike other objects, the Math object has no constructor. <p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"<p><b>Math.E:</b> " + Math.E + "</p>" +
"<p><b>Math.PI:</b> " + Math.PI + "</p>" +
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +
"<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
</script>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.round(4.6);
</script>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.ceil(4.7);
</script>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
</script>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.trunc(4.7);
</script>
<p>Code to create 4 digit random opt number</p>
<button onclick="document.getElementById('demo').innerHTML = getRndInteger(1000,9999)">Click Me</button>
<p id="demo"></p>
<script>
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
</script>
document.getElementById(elementID)
Note :- Any id should be unique, but: document.getElementsByClassName(classname)
getElementsByName()
document.getElementsByTagName(tagname)
Note :- getElementsByTagName("*") returns all elements in the document.document.querySelector(CSS selectors)
document.querySelectorAll(CSS selectors)
<h2 onclick="this.innerHTML='Ooops!'">Click on this text!</h2>
<h2 onclick="changeText(this)">Click on this text!</h2>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
<p id="demo"></p>
<div id="div01" style="border:1px solid black; padding:10px">
<p>Right-click in this box to see the hidden content!</p>
</div>
<div id="myDiv" style="visibility:hidden">
<p>This is Kaushal</p>
<p>from SpecBits</p>
</div>
<script>
// Assign an "contextmenu" event to div01:
document.getElementById("div01").addEventListener("contextmenu", myFunction);
// Prevent default context menu:
const div = document.getElementById("div01");
div.addEventListener("contextmenu", (e) => {e.preventDefault()});
// Show hidden content:
function myFunction() {
const div = document.getElementById("myDiv");
div.style.visibility = "visible";
}
</script>
<p id="demo" ondblclick="myFunction()">Double-click me.</p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "I was double-clicked!";
}
</script>
<p>Assign an "onmouseenter" and "onmouseleave" event to a h1 element.</p>
<h1 id="demo">Mouse over me</h1>
<script>
document.getElementById("demo").onmouseenter = function() {mouseEnter()};
document.getElementById("demo").onmouseleave = function() {mouseLeave()};
function mouseEnter() {
document.getElementById("demo").style.color = "red";
}
function mouseLeave() {
document.getElementById("demo").style.color = "black";
}
</script>
<div onmousemove="myMoveFunction()">
<p>onmousemove</p>
<p id="demo1">Mouse over me!</p>
</div>
<script>
let x = 0;
function myMoveFunction() {
document.getElementById("demo1").innerHTML = x+=1;
}
</script>
<div onmousemove="myMoveFunction()">
<p>onmousemove</p>
<p id="demo1">Mouse over me!</p>
</div>
<div onmouseenter="myEnterFunction()">
<p>onmouseenter</p>
<p id="demo2">Mouse over me!</p>
</div>
<div onmouseover="myOverFunction()">
<p>onmouseover</p>
<p id="demo3">Mouse over me!</p>
</div>
<p>The onmousemove event occurs every time the mouse pointer is moved over an element.</p>
<p>The mouseenter event only occurs when the mouse pointer enters an element. </p>
<p>The onmouseover event occurs when the mouse pointer enters an div element.</p>
<script>
let x = 0;
let y = 0;
let z = 0;
function myMoveFunction() {
document.getElementById("demo1").innerHTML = z+=1;
}
function myEnterFunction() {
document.getElementById("demo2").innerHTML = x+=1;
}
function myOverFunction() {
document.getElementById("demo3").innerHTML = y+=1;
}
</script>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:150px;padding:30px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
obj.innerHTML = "Thank You"
}
function mOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
<div onmousedown="mDown(this)" onmouseup="mUp(this)"
style="background-color:#D94A38;width:100px;height:120px;padding:40px;">
Click Me</div>
<script>
function mDown(obj) {
obj.style.backgroundColor = "#1ec5e5";
obj.innerHTML = "Release Me";
}
function mUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
<p>Press a key in the input field:</p>
<input type="text" id="demo">
<script>
document.getElementById("demo").onkeypress = function() {myFunction()};
function myFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
</script>
Note :-The onkeypress event is deprecated. <p>Press a key in the input field:</p>
<input type="text" onkeydown="myFunction(this)">
<script>
function myFunction(element) {
element.style.backgroundColor = "red";
}
</script>
Note :-The onkeypress event is deprecated. <p>The function transforms the input field to upper case:</p>
Enter your name: <input type="text" id="fname">
<script>
document.getElementById("fname").addEventListener("keyup", myFunction);
function myFunction() {
let x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
Note :-The onkeypress event is deprecated. <input type="text" id="demo" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
<script>
function keydownFunction() {
document.getElementById("demo").style.backgroundColor = "red";
}
function keyupFunction() {
document.getElementById("demo").style.backgroundColor = "green";
}
</script>
<form onsubmit="script">
<p>When you submit the form, a function is triggered which alerts some text.</p>
<form onsubmit="myFunction()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function myFunction() {
alert("The form was submitted");
}
</script>
<form onsubmit="script">
Enter your name: <input type="text" id="fname" onchange="upperCase()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function upperCase() {
const x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
<element onfocus="script">
Enter your name: <input type="text" id="myInput" onfocus="focusFunction()" onblur="blurFunction()">
<script>
// Focus = Changes the background color of input to yellow
function focusFunction() {
document.getElementById("myInput").style.background = "yellow";
}
// No focus = Changes the background color of input to red
function blurFunction() {
document.getElementById("myInput").style.background = "red";
}
</script>
<element onblur="script">
Enter your name: <input type="text" name="fname" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
let x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
window.alert("sometext");
Example
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
Note :- The window.alert() method can be written without the window prefix. window.confirm("sometext");
Example
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
if (confirm("Press a button!")) {
txt = "You pressed OK!";
} else {
txt = "You pressed Cancel!";
}
document.getElementById("demo").innerHTML = txt;
}
</script>
Note :- The window.alert() method can be written without the window prefix. window.prompt("sometext","defaultText");
Example
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
let text;
let person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "") {
text = "User cancelled the prompt.";
} else {
text = "Hello " + person + "! How are you today?";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Note :- The window.alert() method can be written without the window prefix. alert("Hello\nHow are you?");
element.addEventListener(event, function, useCapture);
The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.) <button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
alert("Hello Kaushal");
});
</script>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click", myFunction);
function myFunction() {
alert ("Hello Kaushal , Welcome to Specbits");
}
</script>
<p>Click the button to perform a calculation.</p>
<button id="myBtn">Try it</button>
<p id="demo"></p>
<script>
let p1 = 5;
let p2 = 7;
document.getElementById("myBtn").addEventListener("click", function() {
myFunction(p1, p2);
});
function myFunction(a, b) {
document.getElementById("demo").innerHTML = a * b;
}
</script>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
<div id="myDIV">
<p>This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.</p>
<p>Click the button to remove the div's event handler.</p>
<button onclick="removeHandler()" id="myBtn">Remove</button>
</div>
<p id="demo"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}
function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
</script>
<element onload="script">
<body onload="checkCookies()">
<p id="demo"></p>
<script>
function checkCookies() {
let text = "";
if (navigator.cookieEnabled == true) {
text = "Cookies are enabled.";
} else {
text = "Cookies are not enabled.";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
<element onunload="script">
<element onresize="script">
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The full URL of this page is:<br>" + window.location.href;
</script>
<input type="button" value="Load new document" onclick="newDoc()">
<script>
function newDoc() {
window.location.assign("https://developersarmy.com")
}
</script>
Note :- Go through with the given below window object. <p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
<script>
let myVar = setInterval(myTimer ,1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>