| home / programming / javascript / diaries / 8 |
|
|
These two methods are used for focusing in windows. The blur() method moves the window to the background, behind the main window. The focus() method moves the window to the foreground, on top of the others ("bringing it into focus").
Borrowing from a script by JavaScript expert Danny Goodman, author of the "JavaScript Bible, 5th Edition," and one we used previously, let's look at how these two methods work. Be sure to try these yourself.
Place the following script in an external file (which is preferable) or the
<head> area of a test document. Placing the script in an external
file is preferable because, as with style sheets, it keeps it separate from
the actual structure and content of the document. Several scripts can be placed
in one external file. Just make sure the names of the variables and functions
are not the same. If so, you can just change the names so they won't conflict
with the other scripts.
(Note: in the script below, the colored lines within the winContent function should each be all on one line, i.e., the green lines should all be together on one line, the red lines should all be together on one line.)
var newWin;
function checkWin() {
if (!newWin || newWin.closed) {
newWin=window.open("","","width=300,height=250");
setTimeout("winContent()",100);
}
else {
newWin.focus();
}
}
function winContent() {
var content = "<html><head><title>The Other Window
<\/title><\/head><body>";
content += "<h2>It Worked!<\/h2>";
content += "<p>This window is a sub window of the
main one that opened it.";
content += "<form><input type='button'
value='Bring Main Window to Front',
onclick='self.opener.focus()'><p>";
content += "<input type='button'
value='Move This Window to Back'
onclick='self.blur()'><p>";
content += "<input type='button'
value='Close This Window' onclick='self.close()'>";
content += "<\/form><\/body><\/html>";
newWin.document.write(content);
newWin.document.close();
}
Then, place the following code in the body of the page (the code in brown should all be on one line.).
<form> <input type="button" name="win" value="Open/Re-Focus Window" onClick="checkWin()"><br> </form>
Let's break this down and see what's happening here. It's really not as complicated
as it seems due to the wrapping of several lines. In the function winContent()
and in the code to be placed in the body of the page, each line of a different
color should be combined on one line. Use the button below to see it as it is
supposed to be written.
|
These two methods, blur() and focus() are very useful when working with multiple windows, allowing you to move back and forth between the windows.
| home / programming / javascript / diaries / 8 |
| ||||||||||||||||||||
Created: August 19, 2005
URL: