Prevent JavaScript enabled browsers to follow the link
<a href="#" onclick="window.alert('Welcome to JavaScript!'); return false;">click here</a>
Adding a script dynamically to a page using javascript
<html> <head> <title>JavaScript</title> </head> <body> <script language="JavaScript" type="text/JavaScript"> var s = document.createElement("script"); s.setAttribute("type", "text/JavaScript"); s.setAttribute("language", "JavaScript"); s.setAttribute("src", "script.js"); document.getElementsByTagName("head")[0].appendChild(s); </script> </body> </html>
Create a function to save a page in Favorites and Bookmarks with javascript
Javascript Function:
<script type="text/javascript"> function bookmark(title,url){ if(window.sidebar){ // for firefox window.sidebar.addPanel(title, url, ""); }else if(window.opera && window.print){ // for opera var elem = document.createElement('a'); elem.setAttribute('href',url); elem.setAttribute('title',title); elem.setAttribute('rel','sidebar'); elem.click(); }else if(document.all){// for ie window.external.AddFavorite(url, title); } } </script>
Using the bookmark function:
<a href="javascript:bookmark(document.title,window.location);">Bookmark this page</a> <a href="javascript:bookmark('javascript bookmark','http://www.w3mentor.com');">Bookmark this page</a>
Limit only english characters in Javascript
Javascript function to check for english characters:
<script type="text/javascript"> function isEnglishchar(str){ var orgi_text="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890._-"; var str_length=str.length; var isEnglish=true; var Char_At=""; for(i=0;i<str_length;i++){ Char_At=str.charAt(i); if(orgi_text.indexOf(Char_At)==-1){ isEnglish=false; break; } } return isEnglish; } </script>
Using the function:
<script type="text/javascript"> var str="HEllతె"; if(isEnglishchar(str)==false){ alert("Please enter only english characters"); return false; } </script>
Create a countdown timer that counts back in Javascript
Div to show the countdown timer.
<div id="showRemain"></div>
Javascript code:
<script type="text/javascript"> function countDown(){ var timeA = new Date(); var timeB = new Date("10/31/2000 03:04:05"); var timeDifference = timeB-timeA; if(timeDifference>=0){ timeDifference=timeDifference/1000; timeDifference=Math.floor(timeDifference); var wan=Math.floor(timeDifference/86400); var l_wan=timeDifference%86400; var hour=Math.floor(l_wan/3600); var l_hour=l_wan%3600; var minute=Math.floor(l_hour/60); var second=l_hour%60; var showPart=document.getElementById('showRemain'); showPart.innerHTML=wan+" hour "+hour+" minute " +minute+" Second "+second+""; if(wan==0 && hour==0 && minute==0 && second==0){ clearInterval(iCountDown); } } } var iCountDown=setInterval("countDown()",1000); </script>
Find the width and height of an image with javascript
Find the width and height of the image with javascript.
<script type="text/javascript"> var img_new=new Image(); img_new.src="https://mail.google.com/mail/help/images/logo2.gif"; img_new.onload=function(){ var jsimg_width=img_new.width; var jsimg_height=img_new.height; var jsimg_fileSize=img_new.fileSize; } </script>
Ways to minimize the performance impact of JavaScript
1. Put all script tags at the bottom of the page, just inside of the closing /body tag. This ensures that the page can be almost completely rendered before script execution begins.
2.Group scripts together. The fewer script tags on the page, the faster the page can be loaded and become interactive. This holds true both for script tags loading external JavaScript files and those with inline code.
3. There are several ways to download JavaScript in a nonblocking fashion:
a. Use the defer attribute of the script tag (Internet Explorer and Firefox 3.5+ only)
b. Dynamically create script elements to download and execute the code
c. Download the JavaScript code using an XHR object, and then inject the code into the page
XMLHttpRequest Script Injection
An approach to nonblocking scripts is to retrieve the JavaScript code using an XMLHttpRequest (XHR) object and then inject the script into the page.
var xhr = new XMLHttpRequest(); xhr.open("get", "file1.js", true); xhr.onreadystatechange = function(){ if (xhr.readyState == 4){ if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){ var script = document.createElement("script"); script.type = "text/javascript"; script.text = xhr.responseText; document.body.appendChild(script); } } }; xhr.send(null);
Creating script tag using DOM methods
var script = document.createElement("script"); script.type = "text/javascript"; script.src = "file1.js"; document.getElementsByTagName("head")[0].appendChild(script);
Deferred JavaScript execution
Any script element marked with defer will not execute until after the DOM has been completely loaded; this holds true for inline scripts as well as for external script files.
<html> <head> <title>Script Defer Example</title> </head> <body> <script defer> alert("defer"); </script> <script> alert("script"); </script> <script> window.onload = function(){ alert("load"); }; </script> </body> </html>
In browsers that don’t support defer, the order of the alerts is “defer”, “script”, and “load”. In browsers that support defer, the order of the alerts is “script”, “defer”, and “load”.
Ternary operator in Javascript
As the name suggests the one and only JavaScript ternary operator, the conditional operator, works with three operands. Ternary operator can be best understood with the help of an example.
var x = 1.1; var result = (x > 1.0) ? "X is greater than 1.0" : "X is lesser than 1.0";
In the example, since the value of x is 1.1, result is set to “X is greater than 1.0” because the condition evaluates to true, resulting in the second operand being returned. The format of the conditional operator is as follows:
condition ? value if true; value if false;
The conditional operator becomes, in essence, a shortcut method for the fairly common if-else programming construct.
Do while loop in Javascript
We can use the do-while construct when we want the code to be processed atleast once, irrespective whether the condition is true or false. Unlike the while loop, the do…while loop doesn’t evaluate the conditional expression until the end of the code block. Hence, the block is executed atleast once always.
var intval = 0; do { document.writeln(" Value is : " + intval + "<br />"); intval++; }while(intval < 10)
A do-while loop is an exit-controlled loop where the code is atleast executed once first and then continues executing it till the condition becomes false. As in while construct, we need to maintain appropriate code to update the test expression variable.
While loops in Javascript
The while loop is one of the simplest JavaScript loops that tests a condition at the start of each loop and continues as long as the expression evaluates to true. Hence, a while loop is an entry-controlled loop. We need to include relevant code in the loop that changes the expression to evaluate to false and the loop then terminates.
var intval = 0; while(int < 10) { document.writeln(" Value is : " + intval + "<br />"); intval++; }
One of the test expression variables is updated within the loop until its value exceeds 10. Since the condition is false now, the loop exits. If an appropriate code is not contained within the loop to update the test expression variable then the loop will never exit and the user will get stuck in an infinite loop.
Looping using the for loop in Javascript
We can use a for loop to iterate the code statements enclosed within a loop a set number of times. The statements within the loop are executed till the condition remains true.
The second version of the for loop is a for…in loop, which accesses each element of the array as a separate item. The array can be accessed directly without using its subscripts or indices. The syntax is as follows:
for( variable in object) { … }
The control statement can be used to not only traverse an object’s properties, but also access each property’s value.
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript"> for(docprop in document) { document.writeln (docprop + " = "); eval (" document.writeln(document.. " + docprop + ")"); document.writeln ("<br />"); } </script> </html>
This yields various outputs with different browsers and objects.
For loop in Javascript
We can use a for loop to iterate the code statements enclosed within a loop a set number of times. The statements within the loop are executed till the condition remains true.
The most common for loop which is implemented in most browsers, has three stages: a variable is set to an initial value; it is updated with each loop; and when the value satisfies a specific condition, the loop terminates.
for(var i = 0; I < 10; i++) document.writeln("Welcome to www.w3mentor.com <br />");
The above code traverses a loop 10 times, printing out the message each time. A variable, i, is set to zero. With each run of the loop, the value is verified to see if the condition is satisfied. Once satisfied, the code in the loop is executed and the conditional variable is updated.
JavaScript switch statement
The JavaScript switch statement is used when there are several possible outcomes resulting from a conditional expression. The JavaScript engine evaluates the expression based on the outcome; one or more alternative options are processed.
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript"> var option = 2; switch(option) { case 1 : alert(" You selected option 1. "); break; case 2 : alert(" You selected option 2. "); break; case 3 : alert(" You selected option 3. "); break; default:alert(" Incorrect option selected. "); } </script> </html>
From the top, an expression that returns a value is given in the switch statement. case statements are then evaluated, in sequence from top to bottom, to see if any corresponding matches are found. If a matching case is found, the statements within the particular case statement code block are executed. At this point, the flow of the program either continues processing each statement, or the control of the program can be transferred to the first line following the end of the switch statement using the optional break.
If else statement in Javascript
In many cases, a conditional test is performed, a block of one or more statements is processed, and the flow of the program continues at the end. However, not all logic can be expressed with just one test.
To perform one branch under one condition and another branch for all other situations,
use the if/else construction. The use of else keyword provides for processing an alternative set of statements if the condition being tested evaluates to false.
Example:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript"> var a = 5; var b = 3; if(a > b) { alert("A is greater than B. "); } else { alert("B is greater than A. "); } </script> </html>
If construct in Javascript
Normally the program flow is linear. It takes deliberate action to change this. You can perform some form of conditional test and run a block of code only if the test evaluated to true.
The use of if keyword signals the beginning of the conditional test, and the parenthetical expression encapsulates the test. When you need to perform a special section of script if only one condition is met, use the simple if construction with a conditional expression that tests for the condition.
Example:
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <script type="text/javascript"> var a = 5; var b = 3; if(a > b) { alert("A is greater than B. "); } </script> </html>
Confirm dialog box in Javascript
The confirm dialog box is used to analyze a user’s response to a question. The confirm dialog box will have an OK button and a Cancel button. If the user presses the OK button, true is returned; otherwise false is returned. This method takes only one argument, the string to be displayed to the user.
Syntax:
confirm(string);
Example usage of confirm in javascript:
<html> <head> <title>Using the JavaScript confirm box</title> </head> <body> <script language = "JavaScript"> document.clear // Clears the page if(confirm("Do you really want to delete this file?") == true){ alert("Then we can proceed to deletion!"); } else{ alert("We'll not delete it"); } </script> </body> </html>
Prompt box in Javascript
The prompt box is used to display a dialog box to take user input in the form of a text box. The prompt dialog box takes two arguments: a string of text that is normally displayed as a question to the user and another string of text which is the initial default setting for the text box. The return value from the prompt is the user entered value or a null.
Syntax:
prompt(message); prompt(message, defaultText);
Example:
prompt("What is your age? ", ""); prompt("What is your age? ", age);
Using value returned from prompt box:
<html> <head> <title>Using the JavaScript prompt box</title> </head> <body> <script language = "JavaScript"> var age=prompt("What is your age?", ""); if ( age == null){ // If user presses the cancel button alert("please enter your age"); } else{ alert(age + " is young"); } </script> </body> </html>
