Content Listing:
- How do I open a centered popup or new window?
- How do I force a frameset?
- How do I open a popup or new window?
- How do I disable the right click?
- How do I show and hide layers?
- How can I open two popup/child windows?
- How do I get a pop-up window to always stay on top?
- How do I get a pop-up window to always stay on top (alternate method)?
- How do I close a child window after I click the submit button?
- How do I close the parent/original window from the new/child/popup window?
- Why doesn't Javascript work in my browser?
- What is the difference between Javascript and Java?
- Why do I get an "access denied" error message when I try to control another window/frame with Javascript?
- How do I get variables from the query string?
- How do I password protect a page with JavaScript?
How do I open a centered popup or new window?
function openwin(url, width, height) {
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:
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.
if (top.location == self.location) {
page = "";
for (i in loc) {
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.
pageurl = "main.htm"; //default page to load
loc = top.location.search.substr(1);
if (loc.indexOf("page=") != -1) {
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>
<frame src="main.htm" name="content">
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.
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.
function nrIE() {
function nrOther(e) {
if (document.layers) {
document.onmousedown = nrOther;
else {
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:
<script type="text/javascript">
function displayLayer(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:
<script type="text/javascript">
function displayLayer(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):
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
Code used to get the above functionality done.
<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)
This is the code used to create the "stay on top" effect
<script type="text/javascript">
var popupwin = null;
function popupWin(url,name) {
if (!document.all) {
document.onclick = function() {
</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:
//<![CDATA[
</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
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.
Supose you wanted this to happen from a button, the code will look like as below.
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.,
Now you can create a new ParseQueryString object and use the param or params methods to retrieve the variables.
var pqs = new ParseQueryString();
/* example */
if (pqs.param("age") > 40) {
</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:
-
Use something like Borgtex has done at CodingForums. The general algorithm behind this method is considered to be among the most secure with pure client-side JavaScript; the second method provided is just as secure if not more secure.
-
Use a secure hash algorithm. To do this, you must first have access to some source code which implements a secure hash algorithm in JavaScript. There may be other ones, but the primary one that I've come accross time and time again is Paul Andrew Johnston's excellent script.
The specific source file you need is located here: http://www.pajhome.org.uk/crypt/md5/sha1.js. While you can reference this file on your script, it is preferred that you download a copy and store it locally on your server in the case that Paul's server goes down or is not avialable for whatever reason.
To use this script you must reference it or embed it into one of your scripts; the preferred method would be to simply reference the JavaScript source file — it's done like this:
<script type="text/javascript" src="path/to/script.js"></script>In this example, path/to/script.js is simply what directory and what you named the file. If you choose to use the one on Paul's server, simply reference it like this:
<script type="text/javascript" src="http://www.pajhome.org.uk/crypt/md5/sha1.js"></script>Now that the script has been referenced, you have access to all of the functionality it contains. To generate the hashes for any string you want (e.g., passwords, etc.), it's easiest to go to Paul's JavaScript MD5 index page. Here, there will be a form in which you can enter strings and see the hash for that string.
So for example, if I enter the string
foo
and check its SHA-1 hash, it will be0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33
. Now, after you've referenced the file into your source somehow and have generated secure hashes of the strings you'd like to validate, you still must have a way to check the user's input against the hash of the string you've secured. Here's a fully functional demo (the password isfoobar
):<script type="text/javascript" src="http://www.pajhome.org.uk/crypt/md5/sha1.js"></script>
<script type="text/javascript">
//<![CDATA[// Ask the user for the password.//]]>
var p = prompt('Enter password:', '');
// Check their string against the secure string.
if(hex_sha1(p) == '8843d7f92416211de9ebb963ff4ce28125932878')
{// If it's correct, tell them (likely you'd do something else of course, but this is just a demo)}
alert('Password accecpted');
// More stuff...
// Else, if it was not valid...
else
{alert('Password not accepted.');}
// More stuff...
</script>This can be easily applied to form data as well as just about anything else — just run the function on the string you'd like to validate then check it against the correct hashed string.
Thanks to Jeff for originally introducing this method at the forums.