Javascript
Javascript
DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <script type="text/javascript"> document.write("<p>My First JavaScript</p>"); </script> </body> </html> Change HTML elements with JavaScript <!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <script type="text/javascript"> document.getElementById("demo").innerHTML="My First JavaScript"; </script> </body> </html> An external JavaScript <!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <button type="button" onclick="myFunction()">Try it</button> <p><strong>Note:</strong> The actual script is in an external script file called "myScript.js".</p> <script type="text/javascript" src="myScript.js"></script> </body> </html> JavaScript statements. <!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <p id="myDIV">A DIV.</p>
<script type="text/javascript"> document.getElementById("demo").innerHTML="Hello Dolly"; document.getElementById("myDIV").innerHTML="How are you?"; </script> </body> </html> <!DOCTYPE html> <html> <body> JavaScript blocks. <h1>My Web Page</h1> <p id="demo">A Paragraph.</p> <p id="myDIV">A DIV.</p> <button type="button" onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { document.getElementById("demo").innerHTML="Hello Dolly"; document.getElementById("myDIV").innerHTML="How are you?"; } </script> </body> </html> Single line comments. <!DOCTYPE html> <html> <body> <h1 id="myH1"></h1> <p id="myP"></p> <script type="text/javascript"> // Write to a heading: document.getElementById("myH1").innerHTML="Welcome to my Homepage"; // Write to a paragraph: document.getElementById("myP").innerHTML="This is my first paragraph."; </script> <p><strong>Note:</strong> The comments are not executed.</p> </body> </html> Multiple lines comments. <!DOCTYPE html> <html>
<body> <h1 id="myH1"></h1> <p id="myP"></p> <script type="text/javascript"> /* The code below will write to a heading and to a paragraph, and will represent the start of my homepage: */ document.getElementById("myH1").innerHTML="Welcome to my Homepage"; document.getElementById("myP").innerHTML="This is my first paragraph."; </script> <p><strong>Note:</strong> The comment-block is not executed.</p> </body> </html> Single line comment to prevent execution. <!DOCTYPE html> <html> <body> <h1 id="myH1"></h1> <p id="myP"></p> <script type="text/javascript"> //document.getElementById("myH1").innerHTML="Welcome to my Homepage"; document.getElementById("myP").innerHTML="This is my first paragraph."; </script> <p><strong>Note:</strong> The comment is not executed.</p> </body> </html> Multiple lines comment to prevent execution. <!DOCTYPE html> <html> <body> <h1 id="myH1"></h1> <p id="myP"></p> <script type="text/javascript"> /* document.getElementById("myH1").innerHTML="Welcome to my Homepage"; document.getElementById("myP").innerHTML="This is my first paragraph."; */ </script> <p><strong>Note:</strong> The comment-block is not executed.</p>
</body> </html> JavaScript Variables Declare a variable, assign a value to it, and display it <!DOCTYPE html> <html> <body> <script type="text/javascript"> var firstname; firstname="Hege"; document.write(firstname); document.write("<br />"); firstname="Tove"; document.write(firstname); </script> <p>The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again.</p> </body> </html> If statement <!DOCTYPE html> <html> <body> <p>Click the button to get a "Good day" greeting if the time is less than 20:00. </p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x=""; var time=new Date().getHours(); if (time<20) { x="Good day"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> If...else statement
<!DOCTYPE html> <html> <body> <p>Click the button to get a time-based greeting.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x=""; var time=new Date().getHours(); if (time<20) { x="Good day"; } else { x="Good evening"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> Random link <!DOCTYPE html> <html> <body> <p id="demo"></p> <script type="text/javascript"> var r=Math.random(); var x=document.getElementById("demo") if (r>0.5) { x.innerHTML="<a href='http://w3schools.com'>Visit W3Schools</a>"; } else { x.innerHTML="<a href='http://wwf.org'>Visit WWF</a>"; } </script> </body> </html> Switch statement <!DOCTYPE html> <html>
<body> <p>Click the button to display what day it is today.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var d=new Date().getDay(); switch (d) { case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="Today it's Tuesday"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break; case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> alertbox <!DOCTYPE html> <html> <head> <script type="text/javascript"> function myFunction() { alert("Hello! I am an alert box!"); } </script> </head> <body> <input type="button" onclick="myFunction()" value="Show alert box" />
</body> </html> Alert box with line breaks <!DOCTYPE html> <html> <body> <p>Click the button to demonstrate line-breaks in a popup box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { alert("Hello\nHow are you?"); } </script> </body> </html>
Confirm box <!DOCTYPE html> <html> <body> <p>Click the button to display a confirm box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var r=confirm("Press a button!"); if (r==true) { x="You pressed OK!"; } else { x="You pressed Cancel!"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> promptbox <!DOCTYPE html>
<html> <body> <p>Click the button to demonstrate the prompt box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var name=prompt("Please enter your name","Harry Potter"); if (name!=null) { x="<p>Hello " + name + "! How are you today?</p>"; document.getElementById("demo").innerHTML=x; } } </script> </body> </html> Call a function <!DOCTYPE html> <html> <head> <script type="text/javascript"> function myFunction() { alert("Hello World!"); } </script> </head> <body> <button onclick="myFunction()">Try it</button> <p>By clicking the button above, a function will be called. The function will al ert a message.</p> </body> </html> Function with an argument <!DOCTYPE html> <html> <body> <p>Click the button to call a function with arguments</p> <button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<script type="text/javascript"> function myFunction(name,job) { alert("Welcome " + name + ", the " + job); } </script> </body> </html> Function with an argument 2 <!DOCTYPE html> <html> <head> <script type="text/javascript"> function myfunction(txt) { alert(txt); } </script> </head> <body> <form> <input type="button" onclick="myfunction('Good Morning!')" value="In the Morning"> <input type="button" onclick="myfunction('Good Evening!')" value="In the Evening"> </form> <p> When you click on one of the buttons, a function will be called. The function wi ll alert the argument that is passed to it. </p> </body> </html> Function that returns a value <!DOCTYPE html> <html> <head> <script type="text/javascript"> function myFunction() { return ("Hello world!"); } </script> </head> <body> <script type="text/javascript"> document.write(myFunction())
</script> </body> </html> Function with arguments, that returns a value <!DOCTYPE html> <html> <body> <p>This example calls a function which perfoms a calculation, and returns the re sult:</p> <p id="demo"></p> <script type="text/javascript"> function myFunction(a,b) { return a*b; } document.getElementById("demo").innerHTML=myFunction(4,3); </script> </body> </html> for loop <!DOCTYPE html> <html> <body> <p>Click the button to loop through a block of code five times.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x="",i; for (i=0;i<5;i++) { x=x + "<p>The number is " + i + "</p>"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> Looping through HTML headers <!DOCTYPE html> <html> <body> <p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Try it</button> <div id="demo"></div> <script type="text/javascript"> function myFunction() { var x="",i; for (i=1; i<=6; i++) { x=x + "<h" + i + ">Heading " + i + "</h" + i + ">"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> whileloop <!DOCTYPE html> <html> <body> <p>Click the button to loop through a block of as long as <em>i</em> is less tha n 5.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x="",i=0; while (i<5) { x=x + "<p>The number is " + i + "</p>"; i++; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> do while loop <!DOCTYPE html> <html> <body> <p>Click the button to loop through a block of as long as <em>i</em> is less tha n 5.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x="",i=0;
do { x=x + "<p>The number is " + i + "</p>"; i++; } while (i<5) document.getElementById("demo").innerHTML=x; } </script> </body> </html> break a loop <!DOCTYPE html> <html> <body> <p>Click the button to do a loop with a break.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x="",i=0; for (i=0;i<10;i++) { if (i==3) { break; } x=x + "<p>The number is " + i + "</p>"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> break & continue <!DOCTYPE html> <html> <body> <p>Click the button to do a loop which will skip the step where i=3.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x="",i=0; for (i=0;i<10;i++) { if (i==3) { continue;
} x=x + "<p>The number is " + i + "</p>"; } document.getElementById("demo").innerHTML=x; } </script> </body> </html> Use a for...in statement to loop through the elements of an object <!DOCTYPE html> <html> <body> <p>Click the button to loop through the properties of an object named "person".< /p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var txt=""; var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; } document.getElementById("demo").innerHTML=txt; } </script> </body> </html> acting to the onclick event <!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayDate() { document.getElementById("demo").innerHTML=Date(); } </script> </head> <body> <h1>My First Web Page</h1> <p id="demo">This is a paragraph.</p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html> Acting to the onmouseover event
<!DOCTYPE html> <html> <head> <script type="text/javascript"> function writeText(txt) { document.getElementById("desc").innerHTML=txt; } </script> </head> <body> <img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planet map" /> <map name="planetmap"> <area shape ="rect" coords ="0,0,82,126" onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by fa r the largest objects in our Solar System.')" href ="sun.htm" target ="_blank" alt="Sun" /> <area shape ="circle" coords ="90,58,3" onmouseover="writeText('The planet Mercury is very difficult to study from the E arth because it is always so close to the Sun.')" href ="mercur.htm" target ="_blank" alt="Mercury" /> <area shape ="circle" coords ="124,58,8" onmouseover="writeText('Until the 1960s, Venus was often considered a twin siste r to the Earth because Venus is the nearest planet to us, and because the two pl anets seem to share many characteristics.')" href ="venus.htm" target ="_blank" alt="Venus" /> </map> <p id="desc">Mouse over the sun and the planets and see the different descriptio ns.</p> </body> </html> The try...catch statement <!DOCTYPE html> <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Error description: " + err.message + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); }
} </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> The try...catch statement with a confirm box <!DOCTYPE html> <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) { document.location.href="http://www.w3schools.com/"; } } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> The onerror event <!DOCTYPE html> <html> <head> <script type="text/javascript"> onerror=handleErr; var txt=""; function handleErr(msg,url,l) { txt="There was an error on this page.\n\n"; txt+="Error: " + msg + "\n"; txt+="URL: " + url + "\n"; txt+="Line: " + l + "\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); return true; }
function message() { adddlert("Welcome guest!"); } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> Create a welcome cookie <!DOCTYPE html> <html> <head> <script type="text/javascript"> function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCStri ng()); document.cookie=c_name + "=" + c_value; } function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,365); } } }
</script> </head> <body onload="checkCookie()"> </body> </html> Simple timing <!DOCTYPE html> <html> <body> <p>Click the button to wait 3 seconds, then alert "Hello".</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { setTimeout(function(){alert("Hello")},3000); } </script> </body> </html> Another simple timing <!DOCTYPE html> <html> <head> <script type="text/javascript"> function timedText() { var t1=setTimeout("document.getElementById('txt').value='2 seconds!'",2000); var t2=setTimeout("document.getElementById('txt').value='4 seconds!'",4000); var t3=setTimeout("document.getElementById('txt').value='6 seconds!'",6000); } </script> </head> <body> <form> <input type="button" value="Display timed text!" onclick="timedText()" /> <input type="text" id="txt" /> </form> <p>Click on the button above. The input field will tell you when two, four, and six seconds have passed.</p> </body> </html> iming event in an infinite loop <!DOCTYPE html> <html> <head> <script type="text/javascript"> var c=0; var t; var timer_is_on=0; function timedCount()
{ document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } </script> </head> <body> <form> <input type="button" value="Start count!" onClick="doTimer()"> <input type="text" id="txt"> </form> <p>Click on the button above. The input field will count forever, starting at 0. </p> </body> </html> Timing event in an infinite loop - with a Stop button <!DOCTYPE html> <html> <head> <script type="text/javascript"> var c=0; var t; var timer_is_on=0; function timedCount() { document.getElementById('txt').value=c; c=c+1; t=setTimeout("timedCount()",1000); } function doTimer() { if (!timer_is_on) { timer_is_on=1; timedCount(); } } function stopCount() { clearTimeout(t); timer_is_on=0; } </script>
</head> <body> <form> <input type="button" value="Start count!" onclick="doTimer()" /> <input type="text" id="txt" /> <input type="button" value="Stop count!" onclick="stopCount()" /> </form> <p> Click on the "Start count!" button above to start the timer. The input field wil l count forever, starting at 0. Click on the "Stop count!" button to stop the co unting. Click on the "Start count!" button to start the timer again. </p> </body> </html> A clock created with a timing event <!DOCTYPE html> <html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); } function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> Create a direct instance of an object <!DOCTYPE html> <html> <body> <script type="text/javascript"> personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}
document.write(personObj.firstname + " is " + personObj.age + " years old."); </script> </body> </html> Create an object constructor <!DOCTYPE html> <html> <body> <script type="text/javascript"> function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } myFather=new person("John","Doe",50,"blue"); document.write(myFather.firstname + " is " + myFather.age + " years old."); </script> </body> </html> string object Return the length of string <!DOCTYPE html> <html> <body> <script type="text/javascript"> var txt = "Hello World!"; document.write(txt.length); </script> </body> </html> Style strings <!DOCTYPE html> <html> <body> <script type="text/javascript"> var txt = "Hello World!"; document.write("<p>Big: " + txt.big() + "</p>"); document.write("<p>Small: " + txt.small() + "</p>"); document.write("<p>Bold: " + txt.bold() + "</p>");
document.write("<p>Italic: " + txt.italics() + "</p>"); document.write("<p>Fixed: " + txt.fixed() + "</p>"); document.write("<p>Strike: " + txt.strike() + "</p>"); document.write("<p>Fontcolor: " + txt.fontcolor("green") + "</p>"); document.write("<p>Fontsize: " + txt.fontsize(6) + "</p>"); document.write("<p>Subscript: " + txt.sub() + "</p>"); document.write("<p>Superscript: " + txt.sup() + "</p>"); document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>"); document.write("<p>Blink: " + txt.blink() + " (does not work in IE, Chrome, or S afari)</p>"); </script> </body> </html> Return the position of the first occurrence of a text in a string - indexOf() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to locate where in the string a specifed value occ urs.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var str="Hello world, welcome to the univers."; var n=str.indexOf("welcome"); document.getElementById("demo").innerHTML=n; } </script> </body> </html> Search for a text in a string and return the text if found - match() <!DOCTYPE html> <html> <body> <script type="text/javascript"> var str="Hello world!"; document.write(str.match("world") + "<br />"); document.write(str.match("World") + "<br />"); document.write(str.match("worlld") + "<br />"); document.write(str.match("world!")); </script> </body> </html>
Replace characters in a string - replace() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to replace "Microsoft" with "W3Schools".</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var str="Visit Microsoft!"; var n=str.replace("Microsoft","W3Schools"); document.getElementById("demo").innerHTML=n; } </script> </body> </html>
Date object Use Date() to return today's date and time <!DOCTYPE html> <html> <body> <script type="text/javascript"> var d=new Date(); document.write(d); </script> </body> </html> Use getTime() to calculate the years since 1970 <!DOCTYPE html> <html> <body> <p id="demo">Click the button to display the number of milliseconds since midnig ht, January 1, 1970.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var d = new Date(); var x = document.getElementById("demo"); x.innerHTML=d.getTime(); } </script>
</body> </html> Use setFullYear() to set a specific date <!DOCTYPE html> <html> <body> <p id="demo">Click the button to display a date after changing the year, month, and day of month.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var d = new Date(); d.setFullYear(2020,10,3); var x = document.getElementById("demo"); x.innerHTML=d; } </script> </body> </html> Use toUTCString() to convert today's date (according to UTC) to a string <!DOCTYPE html> <html> <body> <p id="demo">Click the button to display the UTC date and time as a string.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var d = new Date(); var x = document.getElementById("demo"); x.innerHTML=d.toUTCString(); } </script> </body> </html> Use getDay() and an array to write a weekday, and not just a number <!DOCTYPE html> <html> <body> <p id="demo">Click the button to display todays day of the week.</p> <button onclick="myFunction()">Try it</button>
<script type="text/javascript"> function myFunction() { var d = new Date(); var weekday=new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; var x = document.getElementById("demo"); x.innerHTML=weekday[d.getDay()]; } </script> </body> </html> Display a clock <!DOCTYPE html> <html> <head> <script type="text/javascript"> function startTime() { var today=new Date(); var h=today.getHours(); var m=today.getMinutes(); var s=today.getSeconds(); // add a zero in front of numbers<10 m=checkTime(m); s=checkTime(s); document.getElementById('txt').innerHTML=h+":"+m+":"+s; t=setTimeout('startTime()',500); } function checkTime(i) { if (i<10) { i="0" + i; } return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html> Array object create an array
<!DOCTYPE html> <html> <body> <script type="text/javascript"> var i; var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (i=0;i<mycars.length;i++) { document.write(mycars[i] + "<br />"); } </script> </body> </html> Join two arrays - concat() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to join three arrays.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var hege = ["Cecilie", "Lone"]; var stale = ["Emil", "Tobias", "Linus"]; var kai = ["Robin"]; var children = hege.concat(stale,kai); var x=document.getElementById("demo"); x.innerHTML=children; } </script> </body> </html> Join three arrays - concat() <!DOCTYPE html> <html> <body> <script type="text/javascript"> var parents = ["Jani", "Tove"]; var brothers = ["Stale", "Kai Jim", "Borge"]; var children = ["Cecilie", "Lone"]; var family = parents.concat(brothers, children); document.write(family);
</script> </body> </html> Join all elements of an array into a string - join() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to join the array elements into a string.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x=document.getElementById("demo"); x.innerHTML=fruits.join(); } </script> </body> </html> Remove the last element of an array - pop() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to remove the last array element.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.pop(); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> Add new elements to the end of an array - push() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to add a new element to the array.</p>
<button onclick="myFunction()">Try it</button> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.push("Kiwi") var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html>
Reverse the order of the elements in an array - reverse() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to reverse the order of the elements in the array. </p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.reverse(); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> Remove the first element of an array - shift() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to remove the first element of the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> var fruits = ["Banana", "Orange", "Apple", "Mango"]; function myFunction() { fruits.shift(); var x=document.getElementById("demo");
x.innerHTML=fruits; } </script> </body> </html> Select elements from an array - slice() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to extract the second and the third elements from the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1,3); var x=document.getElementById("demo"); x.innerHTML=citrus; } </script> </body> </html> Sort an array (alphabetically and ascending) - sort() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to sort the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> Sort numbers (numerically and ascending) - sort() <!DOCTYPE html> <html> <body>
<p id="demo">Click the button to sort the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var points = [40,100,1,5,25,10]; points.sort(function(a,b){return a-b}); var x=document.getElementById("demo"); x.innerHTML=points; } </script> </body> </html> Sort numbers (numerically and descending) - sort() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to sort the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var points = [40,100,1,5,25,10]; points.sort(function(a,b){return b-a}); var x=document.getElementById("demo"); x.innerHTML=points; } </script> </body> </html> Add an element to position 2 in an array - splice() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"Lemon","Kiwi"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script>
</body> </html> Convert an array to a string - toString() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to convert the array into a String.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.toString(); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> </body> </html> Add new elements to the beginning of an array - unshift() <!DOCTYPE html> <html> <body> <p id="demo">Click the button to add elements to the array.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon","Pineapple"); var x=document.getElementById("demo"); x.innerHTML=fruits; } </script> <p><b>Note:</b> The unshift() method does not work properly in Internet Explorer 8 and earlier, the values will be inserted, but the return value will be <em>un defined</em>.</p> </body> </html> Boolean object Check Boolean value <!DOCTYPE html> <html> <body>
<script type="text/javascript"> var b1=new Boolean(0); var b2=new Boolean(1); var b3=new Boolean(""); var b4=new Boolean(null); var b5=new Boolean(NaN); var b6=new Boolean("false"); document.write("0 is boolean "+ b1 +"<br />"); document.write("1 is boolean "+ b2 +"<br />"); document.write("An empty string is boolean "+ b3 + "<br />"); document.write("null is boolean "+ b4+ "<br />"); document.write("NaN is boolean "+ b5 +"<br />"); document.write("The string 'false' is boolean "+ b6 +"<br />"); </script> </body> </html> Math object Use round() to round a number <!DOCTYPE html> <html> <body> <p id="demo">Click the button to round the number 2.5 to it's nearest integer.</ p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { document.getElementById("demo").innerHTML=Math.round(2.5); } </script> </body> </html> Use random() to return a random number between 0 and 1 <!DOCTYPE html> <html> <body> <p id="demo">Click the button to display a random number.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { document.getElementById("demo").innerHTML=Math.random(); } </script> </body>
</html> Use max() to return the number with the highest value of two specified numbers <!DOCTYPE html> <html> <body> <p id="demo">Click the button to return the highest number of 5 and 10.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { document.getElementById("demo").innerHTML=Math.max(5,10); } </script> </body> </html> Use min() to return the number with the lowest value of two specified numbers <!DOCTYPE html> <html> <body> <p id="demo">Click the button to return the lowest number of 5 and 10.</p> <button onclick="myFunction()">Try it</button> <script type="text/javascript"> function myFunction() { document.getElementById("demo").innerHTML=Math.min(5,10); } </script> </body> </html> Convert Celsius to Fahrenheit <!DOCTYPE html> <html> <head> <script type="text/javascript"> function convert(degree) { if (degree=="C") { F=document.getElementById("c").value * 9 / 5 + 32; document.getElementById("f").value=Math.round(F); } else { C=(document.getElementById("f").value -32) * 5 / 9; document.getElementById("c").value=Math.round(C); }
} </script> </head> <body> <p></p><b>Insert a number into one of the input fields below:</b></p> <form> <input id="c" name="c" onkeyup="convert('C')"> degrees Celsius<br /> equals<br /> <input id="f" name="f" onkeyup="convert('F')"> degrees Fahrenheit </form> <p>Note that the <b>Math.round()</b> method is used, so that the result will be returned as an integer.</p> </body> </html> General Use a for...in statement to loop through the elements of an object <!DOCTYPE html> <html> <body> <p>Click the button to loop through the properties of an object named "person".< /p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var txt=""; var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; } document.getElementById("demo").innerHTML=txt; } </script> </body> </html> Javascript browser object Window Object Display an alert box <!DOCTYPE html> <html> <head> <script type="text/javascript"> function myFunction() { alert("Hello! I am an alert box!");
} </script> </head> <body> <input type="button" onclick="myFunction()" value="Show alert box" /> </body> </html> Display an alert box with line-breaks <!DOCTYPE html> <html> <body> <p>Click the button to demonstrate line-breaks in a popup box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { alert("Hello\nHow are you?"); } </script> </body> </html> Display a confirm box, and alert what the visitor clicked <!DOCTYPE html> <html> <body> <p>Click the button to display a confirm box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var r=confirm("Press a button!"); if (r==true) { x="You pressed OK!"; } else { x="You pressed Cancel!"; } document.getElementById("demo").innerHTML=x; } </script>
</body> </html> Display a prompt box <!DOCTYPE html> <html> <body> <p>Click the button to demonstrate the prompt box.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> <script type="text/javascript"> function myFunction() { var x; var name=prompt("Please enter your name","Harry Potter"); if (name!=null) { x="<p>Hello " + name + "! How are you today?</p>"; document.getElementById("demo").innerHTML=x; } } </script> </body> </html> Create a pop-up window Open a new window when clicking on a button <!DOCTYPE html> <html> <head> <script type="text/javascript"> function open_win() { window.open("http://www.w3schools.com"); } </script> </head> <body> <form> <input type="button" value="Open Window" onclick="open_win()"> </form> </body> </html>
<html> <head> <script type="text/javascript"> function open_win() { window.open("http://www.w3schools.com","_blank","toolbar=yes, location=yes, dire ctories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=ye s, width=400, height=400"); } </script> </head> <body> <form> <input type="button" value="Open Window" onclick="open_win()"> </form> </body> </html> Open multiple new windows <!DOCTYPE html> <html> <head> <script type="text/javascript"> function open_win() { window.open("http://www.microsoft.com/"); window.open("http://www.w3schools.com/"); } </script> </head> <body> <form> <input type="button" value="Open Windows" onclick="open_win()"> </form> </body> </html> Assure that the new window does NOT get focus (send it to the background) <!DOCTYPE html> <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is 'myWindow'</p>"); myWindow.blur(); } </script> </head> <body> <input type="button" value="Open window" onclick="openWin()" />
</body> </html>