Header Image

JavaScript FAQs - Answered!

Content Listing:


How do I open a centered popup or new window?

<script type="text/javascript">
function openwin(url, width, height) {
var name = "popup"; // popup name
var width = width; // popup width
var height = height; // popup height
var left = (screen.width - width) / 2 ;
var top = (screen.height - height) / 2;
var windowproperties = "width="+ width +",height="+ height +",left="+ left +",top="+ top +",scrollbars=1";
window.open(url, name, windowproperties);
}
</script>

You then use a link like this to open the window:

<a href="http://www.webdevfaqs.com" onClick="openwin(this.href,'600','400'); return false;">Open a centered popup window</a>

this.href: this part tells the script to use the current link in the <a> tag.
'600': this is the width of the window.
'400': this is the height of the window.

Example:
Open a centered popup window

More info on popups can be found here.


How do I force a frameset?

With frames pages, people often have a problem when a user tries to load a framed page, without it's frameset. This can happen if the user comes to the page via a search engine, and they will end up not having the frame with the links necessary to navigate the site. What we need to do is use JavaScript to detect if the page is inside it's frameset.

This code goes on each framed page that we do not want to be able to view outside the frameset.

<script type="text/javascript">
if (top.location == self.location) {
loc = window.location.href.split("/").slice(3);
page = "";
for (i in loc) {
page += "/"+loc[i];
}
top.location.href = "/index.htm?page="+page;
}
</script>

It is recommended to use an absolute link to the index.htm page (or whichever page sets up your frames) as we have. The reason for this, is if it is a relative link, the script will stop working in subdirectories, etc.

And this code goes on your index.htm page.

<script type="text/javascript">
pageurl = "main.htm"; //default page to load
loc = top.location.search.substr(1);
if (loc.indexOf("page=") != -1) {
loc = loc.split("page=");
pageurl = loc[1].substring(0,(loc[1].indexOf("&") == -1) ? loc[1].length : loc[1].indexOf("&"));
}
document.write('<frameset cols="200,*">',
'<frame src="nav.htm" name="nav">',
'<frame src="' + pageurl + '" name="content">',
'</frameset>');
</script>
<!--set up noscript frameset for those without javascript-->
<noscript>
<frameset cols="200,*">
<frame src="nav.htm" name="nav">
<frame src="main.htm" name="content">
</frameset>
</noscript>

Pay attention to the parts in bold as those are the names of the pages. You will need to customize those to point to your pages


How do I open a popup or new window?

Opening a popup window in JavaScript is quite easy. The sample code below will show you how to do it, and the various elements will be described below.

<a href="http://www.webdevfaqs.com" onclick="window.open(this.href,'child','width=600,height=400,scrollbars=1'); return false;">Open popup</a>

First of all, we start with a normal link. This will keep the link working for those with javascript disabled. There are three parts that you need to pay attention to:

this.href: this part tells the script to use the current link in the <a> tag.
"child": this is the name of the popup window.
width=400,height=300": these are the properties for the window.

Here are the different values you can use for the window properties:

width=400 The width of the window in pixels.
height=300 The height of the window in pixels.
left=50 The position of the window in pixels from the left of the browser.
top=50 The position of the window in pixels from the top of the browser.
resizeable=yes or no (or 1 or 0) Used to specify if the window is resizable.
scrollbars=yes or no (or 1 or 0) Used to specify if the window has scrollbars.
toolbar=yes or no (or 1 or 0) Used to specify if the window has the toolbar (back, forward, etc...).
location=yes or no (or 1 or 0) Used to specify if the window has the location bar.
directories=yes or no (or 1 or 0) Used to specify if the window should show extra buttons(personal bar, what's cool, etc...).
status=yes or no (or 1 or 0) Used to specify if the window has the status bar.
menubar=yes or no (or 1 or 0) Used to specify if the window has the menu bar (File, Edit, etc...).
copyhistory=yes or no (or 1 or 0) Used to specify if the window should copy the old window's history.

Note that if you do not specify a property (ie. leave it blank) it will default to no (or 0).

Example:
Open popup


How do I disable the right click?

Note that disabeling the right click won't stop people from getting your images or source code. You may want to read about protecting your images and protecting your source before you use a script such as the one below.

<script type="text/javascript">
function nrIE() {
if (document.all) {
return false;
}
}
function nrOther(e) {
if (document.layers||!document.all) {
if (e.which==2||e.which==3) {
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
document.onmousedown = nrOther;
}
else {
document.onmouseup = nrOther;
document.oncontextmenu = nrIE;
}
document.oncontextmenu = new Function("return false");
</script>

How do I show and hide layers?

You have two options to show/hide layers. You can use the css property visibility or display. The visibility propery takes up space on the page even when it is not visible, but display does not take up space when it is not visible.

Example using the display property:

<head>
<script type="text/javascript">
function displayLayer(which) {
obj = document.getElementById(which);
obj.style.display == "block" ? obj.style.display = "none" : obj.style.display = "block";
}
</script>
</head>
<body>
<a href="#" onclick="displayLayer('mydiv'); return false;">Display</a><br>
<div id="mydiv" style="display:none;">This is the div to either display or hide.</div>
Text to show what happens.

Example using the visibility property:

<head>
<script type="text/javascript">
function displayLayer(which) {
obj = document.getElementById(which);
obj.style.visibility == "visible" ? obj.style.visibility = "hidden" : obj.style.visibility = "visible";
}
</script>
</head>
<body>
<a href="#" onclick="displayLayer('mydiv'); return false;">Display</a><br>
<div id="mydiv" style="display:none;">This is the div to either display or hide.</div>
Text to show what happens.

The two parts that you will want to change to make this script work on your pages are these:

onclick="displayLayer('mydiv'); This part (mydiv) should point to the ID of the div below.
<div id="mydiv" ...> This part (mydiv) is referenced in the link above.

Example (uses the display method):

Display

Text to show what happens.


How can I open two popup/child windows?

There is one most important thing to keep in mind when opening multiple child/popup windows, and that is to make sure that the window name parameter, which is the second parameter in the window.open('url','name','properties') method, is different for each window. If you have the same name for any number of windows , they all will open in one window.

Below is an example that opens multiple popup windows

Open Window 1
Open Window 2

Code used to get the above functionality done.

<a href="http://www.webdevfaqs.com" onclick="window.open(this.href,'win1'); return false;">Open Window 1</a>
<a href="http://forums.webdeveloper.com" onclick="window.open(this.href,'win2') return false;">Open Window 2</a>

How do I get a pop-up window to always stay on top?

Note: You may want to consider the alternate method.

This is a bit tricky. The most popular way to get a child window to stay in focus is considered this statement
onblur = self.focus();
The above will work with out any problems only in IE browsers, more precisely with the modal dialogue windows
window.showModalDialog(URL [, arguments [, features]]):
The problem with the this is that window.showModalDialog does not work with NS browsers at all and
the onblur=self.focus(); does not necessarily work with NS as well. This is the work around to make it work for both IE and NS browsers. This will work with reference to the parent window that opens a child window and child window will remain on top of the parent window. Add the following code in the parent window (the <head> section, preferably)

Open window

This is the code used to create the "stay on top" effect

<head>
<script type="text/javascript">
var popupwin = null;
function popupWin(url,name) {
popupwin = window.open(url,name,'width=600,height=400');
}
if (!document.all) {
document.captureEvents (Event.CLICK);
}
document.onclick = function() {
if (popupwin != null && !popupwin.closed) {
popupwin.focus();
}
}
</script>
</head>
<body>
<a href="http://www.webdevfaqs.com" onclick="popupWin(this.href,'win1'); return false;">Open window</a>
</body>

However, you can use this line of code onblur = self.focus(); in the body tag and it will work in IE browsers.
<body onblur = "self.focus();"> and this will cause the page to be in focus (No effect in NS browsers).


How do I get a pop-up window to always stay on top (alternate method)?

Sometimes, for whatever reason (usually when you want to emulate the proprietary modal dialogs), you want a child window (or the parent window) to be on the top of the window stack at all times (think the "always on top" feature in some applications). You can call the window's focus method to achieve this. Consider the following code:

<script type="text/javascript">
//<![CDATA[
onblur = function() { setTimeout(focus, 10); }
//]]>
</script>

This simply listens for an onblur event on the window (when the window loses focus, this could occur if another window gains focus, or the window is minimized, for example), and assigns an annoymous (a function with no name to it). This function then waits 10 milliseconds and requests focus for the window which results in the window being focused (on top of the window stack).


How do I close a child window after I click the submit button?

Just add self.close(); wherever you want this to happen, i.e if you wanted a button to close the child window, it will look like this

<input type="button" value="submit" onclick="self.close();">

How do I close the parent/original window from the new/child/popup window?

Add the following code snippet in the event call of the child window html element form where you want parent to be closed.

top.opener.close();

Supose you wanted this to happen from a button, the code will look like as below.

<input type="button" value="submit" onclick="top.opener.close();">

Why doesn't Javascript work in my browser?

You may have Javascript disabled. For IE, you can enable it by clicking Tools > Internet Options > Security > Custom Level, then scrolling down and enabling all the options in the 'Scripting' category. For Mozilla or similar browsers, click Edit > Preferences > Advanced > Scripts & Plugins and check the boxes.

Alternately, there may be a problem with your browser, requiring a reinstall. You can download the latest version of Microsoft Internet Explorer from http://www.microsoft.com/downloads/, Mozilla from http://www.mozilla.org/, or Opera from http://www.opera.com/download/.

If only some features of Javascript malfuction, it may be due to a popup blocker you have installed, or (in browsers such as Mozilla or Opera) security restrictions preventing certain features from working, such as the inbuilt popup blockers. Try disabling these features and accessing a Javascript-based site.


What is the difference between Javascript and Java?

There seems to be a lot of confusion on this topic, perhaps because the two languages share a common syntax (both based on C) and a partial name (JavaScript was originally called LiveScript, but it was renamed as Java became popular).

Javascript (also known as Jscript) is a scripting language similar to ECMAScript. It is usually found embedded in or linked to webpages, working within the browser to create "dynamic" effects such as image rollovers, hovering menus, and so on. It is a powerful language, but because of built in security restrictions and incompatibilities between various browsers/versions it may not be used to its full potential. Bear in mind that Javascript does not have to appear in webpages, and can occur in other applications or independently.

Java is a compiled (sort of) programming language, which can be used to create "applets" that are embedded in webpages. However, it is fully capable in its own right and can also be used for normal applications. It is designed to be platform-independent, and accomplishes this by compiling to a bytecode instead of normal machine code; this means it must be interpreted and is slower than a native application (for instance, compiled in C). When embedded in webpages, Java applets are usually used for more complex operations than Javascript since they can perform networking, 3D graphics and other similar tasks much more easily.

Summary: when posting on the forums, please be clear which language you mean. Bear in mind there are many more JavaScript users than Java ones, and for the latter you may be better off asking at a dedicated Java forum such as http://forum.java.sun.com/.

References:

http://devedge.netscape.com/central/javascript/ - JavaScript documentation (Netscape Devedge)

http://java.sun.com/ - Main Java site (Sun)


Why doesn't Javascript work in my browser?

You may have Javascript disabled. For IE, you can enable it by clicking Tools > Internet Options > Security > Custom Level, then scrolling down and enabling all the options in the 'Scripting' category. For Mozilla or similar browsers, click Edit > Preferences > Advanced > Scripts & Plugins and check the boxes.

Alternately, there may be a problem with your browser, requiring a reinstall. You can download the latest version of Microsoft Internet Explorer from http://www.microsoft.com/downloads/, Mozilla from http://www.mozilla.org/, or Opera from http://www.opera.com/download/.

If only some features of Javascript malfuction, it may be due to a popup blocker you have installed, or (in browsers such as Mozilla or Opera) security restrictions preventing certain features from working, such as the inbuilt popup blockers. Try disabling these features and accessing a Javascript-based site.


Why do I get an "access denied" error message when I try to control another window/frame with Javascript?

This is due to security restrictions built into browsers, to prevent pages from one domain interfering with those in another; it is known as the "same origin policy" (see http://www.mozilla.org/projects/security/components/same-origin.html). The rules are explained in more detail on that page, but basically require pages to have the same domain, port and protocol to interact.

Depending on what you are trying to do, you may be able to use a server-side script to read the remote pages and present them as you wish, or you may need to find an alternative method. If you are coding for a known environment (such as an intranet) you may be able to disable the same origin policy, depending on your browser.


How do I get variables from the query string?

You may use this JS library to do the job for you.

First, import the library into your HTML document. e.g.,

<script type="text/javascript" src="http://www.yoursite.com/ParseQueryString.js"></script>

Now you can create a new ParseQueryString object and use the param or params methods to retrieve the variables.

<script type="text/javascript">
var pqs = new ParseQueryString();
/* example */
if (pqs.param("age") > 40) {
alert("Over the hill");
}
</script>

Refer to the reference page included in the RAR archive for more details about using this library.

Download ParseQueryString.zip.


How do I password protect a page with JavaScript?

It is common to want to have a certain file or page be protected. However, this isn't always possible in the most practical manner which would generally be using a server-side technology to protect it. In that case, you can use JavaScript to do this securely. There are two methods that can be used:

Thanks to Jeff for originally introducing this method at the forums.