Back to Programming main page
JavaScript
Moving elements when the user scrolls
Description Make a layer stay in the visible area of the web page, even when the user scrolls. Sections in the code are included to make the position change when the window is resized. This is useful if you want to have an item always at in the bottom of the screen, for example, like on this website.
Instructions Put InitMenuFollow() into the <body> onload attribute. Create a layer with ID ‘MovingSection’.
Compatability Tested in PC IE 6, Mac IE 5, Firefox and Safari (Mac).
Show/hide code View example
This site also uses the code, as well as finding the window height. View JavaScript.
// NB Uncomment the sections marked
/* Window resizing code */
// to make the top position recalculate when the user
// resizes the window. This is useful if, say, you always
// want something to display in the bottom corner of the page.
var OriginalTopPos;
var OriginalWinHeight;
/* Window resizing code
var ScrollAmount;
*/
function InitMenuFollow()
// 1. Get the initial vertical position of the MovingSection object.
// 2. Set a timer to run the ScrollMonitor procedure
{
// NB You can only get the position of an element if it has been set
// previously via CSS or JavaScript.
OriginalTopPos = document.getElementById("MovingSection").style.top;
/* Window resizing code
// Set the inital height of the window. This must be done now, rather than
// when the global variable was declared, otherwise Firefox reports 0
// height presumably because the page hasn't yet loaded.
OriginalWinHeight = GetWinHeight();
*/
// Run ScrollMonitor every second
// setInterval syntax is (function to run, frequency to run it (in ms), function parameters).
// function to run can be FunctionName or "FunctionName()" in most browsers - but only
// the latter in Mac IE5.
window.setInterval ("ScrollMonitor()", 1000);
}
function ScrollMonitor()
// Makes sure the layer called "MovingSection" is always "OriginalTopPos"
// down from the top of the window
// Bugs: Could make the page infinitely scrollable - the layer shouldn't move if it's
// at the bottom of the web page
{
// Find out how far the user has scrolled (method varies...)
if (document.documentElement && document.documentElement.scrollTop)
// PC IE6 strict, Mac IE 5, Mac Firefox strict
ScrollAmount = document.documentElement.scrollTop;
else if (document.body && document.body.scrollTop)
// Safari, PC IE6 trans, Mac Firefox trans
ScrollAmount = document.body.scrollTop;
else if (window.scrollY)
// Mozilla browsers (incl. Firefox and Safari) understand this one,
// though they've probably already got the value.
ScrollAmount = window.scrollY;
else
ScrollAmount = 0;
// Move box down by the scroll amount. OriginalTopPos may be false rather
// than a number if GetWinHeight could not detect the value. Assume a
// figure to prevent errors.
if(!OriginalTopPos)OriginalTopPos=200;
document.getElementById("MovingSection").style.top = parseInt(OriginalTopPos) + parseInt(ScrollAmount) + "px";
}
/* Window resizing code
function WindowResize()
{
// Set new 'original' defaults
OriginalTopPos = parseInt(OriginalTopPos) + (GetWinHeight()-OriginalWinHeight);
OriginalWinHeight = GetWinHeight();
document.getElementById("MovingSection").style.top = OriginalTopPos + "px";
}
window.onresize = WindowResize;
*/
/* Window resizing code
function GetWinHeight()
{
// Return the height of the visible area.
// Assumes the document is HTML strict.
var appVersion = navigator.appVersion;
// Get platform
var Platform;
var PlatformPattern1 = /mac/i;
var PlatformPattern2 = /windows/i;
if(appVersion.match(PlatformPattern1))Platform="mac";
else if(appVersion.match(PlatformPattern2))Platform="windows";
else Platform="unknown";
// Get browser make
var userAgent = navigator.userAgent;
var Browser="";
var BrowserPattern = /(msie)|(safari)|(firefox)/i;
Browser = userAgent.match(BrowserPattern)[0].toLowerCase();
if(Browser=="")Browser="mozilla";
if((Platform=="windows"&&Browser=="msie")||(Browser=="firefox")) return document.documentElement.clientHeight;
else if(Platform=="mac"&&Browser=="msie") return document.body.clientHeight;
else if(Browser=="safari") return document.clientHeight;
else return false;
}
*/
Showing/hiding
Description Make a web page element disappear or appear
Instructions Give your element an ID then run the function in an onclick attribute. For example, ShowHide('divLayer1','reverse','reflow')
Compatability Works with all browsers as long as the element you are working on can be shown/hidden by the browser. For Netscape 4 this means using the <layer> tag.
Show/hide code Example: this very page shows/hides <div> tags containing the code snippets
function ShowHide()
{
// CROSS-BROWSER, GENERIC
// Hide or show the object - the method used depends on the user's browser.
// First parameter: name of object to show/hide
// Second parameter: whether to hide, show or reverse the current status of the object.
// Values are: 'hidden', 'visible', 'reverse'
// Second param is optional if a third parameter is not supplied. When left out, the
// second param defaults to 'reverse'
// Third parameter: if to affect surrounding content - 'reflow' or 'fixed'
// Defaults to 'reflow'
// When 'reflow', content below the object moves up or down depending on whether
// the object is visible or not. This uses (for W3C) the display style property.
// When 'fixed', showing or hiding the object does not affect other parts of the
// page. This uses (for W3C) the visibility style propery.
// E.g. ShowHide('divLayer1') or ShowHide('divLayer1','visible') or
// ShowHide('divLayer1','reverse','chkBox1')
// Get arguments
Args = ShowHide.arguments;
// If the first argument doesn't exist, leave function
if(Args.length>0) Args = new Array(Args[0], Args[1], Args[2]);
else return false;
switch (Args[1])
{
case 'hidden':
// If the second argument is 'hidden', hide the object using the method appropriate to the browser
if(Args[2] == 'fixed')
{
// Use the visibility property
if(document.getElementById) document.getElementById(Args[0]).style.visibility = 'hidden';
else if(document.all[Args[0]]) document.all[Args[0]].style.visibility = "hidden";
else if(document.layers) document.layers[Args[0]].visibility = "hide";
else return false;
}
else
{
// Use the display property
if(document.getElementById) {document.getElementById(Args[0]).style.display = 'none';}
else if(document.all[Args[0]]) document.all[Args[0]].style.display = "none";
else if(document.layers) document.layers[Args[0]].visibility = "hide";
else return false;
}
break;
case 'visible':
// If the second argument is 'visible', hide the object using the method appropriate to the browser
if(Args[2] == 'fixed')
{
if(document.getElementById) document.getElementById(Args[0]).style.visibility = 'visible';
else if(document.all[Args[0]]) document.all[Args[0]].style.visibility = "visible";
else if(document.layers) document.layers[Args[0]].visibility = "show";
else return false;
}
else
{
if(document.getElementById) document.getElementById(Args[0]).style.display = 'block';
else if(document.all[Args[0]]) document.all[Args[0]].style.display = "block";
else if(document.layers) document.layers[Args[0]].visibility = "show";
else return false;
}
break;
default:
// Else if the object is current visible set to hidden else set to visible
if(document.getElementById)
{
// Use getElementByID method for IE5+ and NS6+ (W3C standard)
if(Args[2] == 'fixed')
{
if(document.getElementById(Args[0]).style.visibility == 'visible') document.getElementById(Args[0]).style.visibility = 'hidden';
else document.getElementById(Args[0]).style.visibility = 'visible';
}
else
{
if(document.getElementById(Args[0]).style.display == 'block') document.getElementById(Args[0]).style.display = 'none';
else document.getElementById(Args[0]).style.display = 'block';
}
}
else
{
if(document.all[Args[0]])
{
if(Args[2] == 'fixed')
{
// Use document.all method for older IE
if(document.all[Args[0]].style.visibility == 'visible') document.all[Args[0]].style.visibility = 'hidden';
else document.all[Args[0]].style.visibility = 'visible';
}
else
{
if(document.all[Args[0]].style.display == 'block') document.all[Args[0]].style.display = 'none';
else document.all[Args[0]].style.display = 'block';
}
}
else
{
// Try to use NS4 layers
if(document.layers[Args[0]])
{
if(document.layers[Args[0]].visibility = "show") document.layers[Args[0]].visibility = "hide";
else document.layers[Args[0]].visibility = "show";
}
else
{
// Give up
return false;
} // give up
} // NS
} // IE4
} // end of Switch
} // END FUNCTION
Showing/hiding depending on window width
Description Make a web page element disappear or appear depending on the width of the user’s browser
Instructions Add the code shown. The parameters for ShowHideWinWidth are the ID of the item to show/hide and the width of the window below which the item is hidden.
Compatability Tested in PC IE 6, Mac IE 5, Firefox and Safari (Mac).
Show/hide code Example
function ShowHideWinWidthWrapper(){ShowHideWinWidth('Section','800')}
// Run on first load to decide whether to hide or not
ShowHideWinWidthWrapper()
// Run when the window is resized. Note that is it not possible
// to run a function with parameters here, hence the
// ShowHideWinWidthWrapper that does the calling of the
// function which actually does the work
window.onresize = ShowHideWinWidthWrapper;
function ShowHideWinWidth()
// Show or hide the supplier object depending on the width of the window.
// Parameter 1: object o hide/show.
// Parameter 2: width to hide. If the window width is greater than this, the object is shown.
// If no object is given, leave. If no width is given, default to 700px.
{
// Get arguments
Args = ShowHideWinWidth.arguments;
// If first object is nothing, leave
if(Args.length>0) Args = new Array(Args[0], Args[1]);
else return false;
// If the second object is nothing, set to 700
if(!Args[1]) Args[1] = 700;
// Get width of window. Modern browsers understand the first line, NS requires the user of the
// innerWidth property. Both return the width of the usuable document area in the browser -
// i.e. not including scroll bars etc.
if(document.body) {var WindowWidth = document.body.clientWidth;}
else if(window.innerWidth) {var WindowWidth = window.innerWidth;}
if(WindowWidth >= Args[1]) {ShowHide(Args[0],'visible');} else {ShowHide(Args[0],'hidden');}
}
Find the visible height or document height
Description Find either the height of the visible area or the total height of a web page
Instructions This is not as simple as it should be; see this separate page for full detail.
Compatability Every browser works differently but they should all be able to tell you window or browser height one way or another. The code and example should hopefully work on your browser.
Show/hide code Example
var OriginalTopPos;
var OriginalWinHeight;
var ScrollAmount;
function InitMenuFollow()
// 1. Get the initial vertical position of the MovingSection object.
// 2. Set a timer to run the ScrollMonitor procedure
{
// NB You can only get the position of an element if it has been set
// previously via CSS or JavaScript.
OriginalTopPos = document.getElementById("WinHeight").style.top;
// Set the inital height of the window. This must be done now, rather than
// when the global variable was declared, otherwise Firefox reports 0
// height presumably because the page hasn't yet loaded.
OriginalWinHeight = GetWinHeight();
// Run ScrollMonitor every second
// setInterval syntax is (function to run, frequency to run it (in ms), function parameters).
// function to run can be FunctionName or "FunctionName()" in most browsers - but only
// the latter in Mac IE5.
window.setInterval ("ScrollMonitor()", 500);
}
function ScrollMonitor()
// Makes sure the layer called "MovingSection" is always "OriginalTopPos"
// down from the top of the window
// Bugs: Makes the page infinitely scrollable - the layer shouldn't move if it's
// at the bottom of the web page
{
// Find out how far the user has scrolled (method varies...)
if (document.documentElement && document.documentElement.scrollTop)
// PC IE6 strict, Mac IE 5, Mac Firefox strict
ScrollAmount = document.documentElement.scrollTop;
else if (document.body && document.body.scrollTop)
// Safari, PC IE6 trans, Mac Firefox trans
ScrollAmount = document.body.scrollTop;
else if (window.scrollY)
// Mozilla browsers (incl. Firefox and Safari) understand this one,
// though they've probably already got the value.
ScrollAmount = window.scrollY;
else
ScrollAmount = 0;
// Move box down by the scroll amount. OriginalTopPos may be false rather
// than a number if GetWinHeight could not detect the value. Assume a
// figure to prevent errors.
if(!OriginalTopPos)OriginalTopPos=200;
document.getElementById("WinHeight").style.top = parseInt(OriginalTopPos) + parseInt(ScrollAmount) + "px";
}
function WindowResize()
{
// Set new 'original' defaults
OriginalTopPos = parseInt(OriginalTopPos) + (GetWinHeight()-OriginalWinHeight);
OriginalWinHeight = GetWinHeight();
document.getElementById("WinHeight").style.top = OriginalTopPos + "px";
}
window.onresize = WindowResize;
function GetDocHeight()
{
if(document.documentElement.scrollHeight)
return document.documentElement.scrollHeight;
else
// Can't return height, e.g. IE Mac. Take a guess
return 2000;
}
function GetWinHeight()
{
// Return the height of the visible area.
// Assumes the document is HTML strict.
var appVersion = navigator.appVersion;
// Get platform
var Platform;
var PlatformPattern1 = /mac/i;
var PlatformPattern2 = /windows/i;
if(appVersion.match(PlatformPattern1))Platform="mac";
else if(appVersion.match(PlatformPattern2))Platform="windows";
else Platform="unknown";
// Get browser make
var userAgent = navigator.userAgent;
var Browser="";
var BrowserPattern = /(msie)|(safari)|(firefox)/i;
Browser = userAgent.match(BrowserPattern)[0].toLowerCase();
if(Browser=="")Browser="mozilla";
if((Platform=="windows"&&Browser=="msie")||(Browser=="firefox")) return document.documentElement.clientHeight;
else if(Platform=="mac"&&Browser=="msie") return document.body.clientHeight;
else if(Browser=="safari") return document.clientHeight;
else return false;
}
document.getElementById("DocHeight").style.height = GetDocHeight() + "px";
document.getElementById("WinHeight").style.top = (GetWinHeight() - 100) + "px";
Create a popup help box
Description Make a <div> block appear on the screen near to where the user clicks, perhaps to provide help
Instructions Create your help box with a <div> tag, ID ‘divHelpTitle’, and another inside called ‘divHelp’. Activate the popup box with a line such as <a href="javascript:void(0);" onclick="HelpPopup('You have clicked on the link to display this text.',event);">Click here</a>
Compatability Works correctly in: IE 4+ (Mac and PC), Firefox, Safari (Mac). For older browsers such as Netscape 4 an alert box appears instead, showing the user the help message.
Show/hide code Example
Using outerHTML (method 1: custom function)
Description All web browsers allow the text between the tags to be modified via innerHTML. IE sensibly also supports outerHTML for making changes to the tags themselves in addition to the inner HTML. For other browsers, and to follow the W3C standard, there are workarounds.
Instructions Instead of using outerHTML, run the function shown here
Compatability Works with all modern browsers
Show/hide code Example
<script type="text/javascript">
function SetOuterHTML (ElementID, txt)
{
// Netscape browsers don't support 'outerHTML', but DOM Level 2 allows a (more complex) workaround.
// (http://www.faqts.com/knowledge_base/view.phtml/aid/970)
var someElement = document.getElementById(ElementID);
if(someElement.outerHTML)
{
// The browser supports Microsoft's outerHTML, so use that
someElement.outerHTML = txt;
}
else
{
// The browser doesn't support outerHTML, try an alternative
// Create a range
var range = document.createRange();
// Set the range's starting point to where the HTML needs to be inserted
// SetStartAfter seems to do the same thing in this case.
range.setStartBefore(someElement);
// Create a fragment from the HTML
var docFrag = range.createContextualFragment(txt);
// Go to the parent node and replace the element with the new HTML fragment
// For innerHTML simulation use someElement.appendChild(docFrag);
someElement.parentNode.replaceChild(docFrag,someElement);
}
}
</script>
Using outerHTML (method 2: prototype)
Description New versions of Netscape (supporting JavaScript 1.5) allow emulation via ‘prototypes’. This method is far less flexible than the previous method.
Instructions Include the prototype setter JavaScript shown here. When code references outerHTML, Netscape will act as though it understands.
Compatability Works in Firefox and other Netscape browsers that support JavaScript 1.5 (not Safari). Does not work in IE but doesn’t need to, though IE5 (Mac) displays an error message.
Show/hide code Example
<script type="text/javascript" LANGUAGE="JavaScript1.5">
if (navigator.appName == 'Netscape')
{
HTMLElement.prototype.outerHTML setter =
function (html)
{
this.outerHTMLInput = html;
var range = this.ownerDocument.createRange();
range.setStartBefore(this);
var docFrag = range.createContextualFragment(html);
this.parentNode.replaceChild(docFrag, this);
}
}
</script>
Detecting browser details
Description Find the user’s browser name, maker, version, codebase and platform. Note that it is usually better to test if something exists rather than go by browser type as new versions and different browsers may not work in the way you expect. For example, see if the browser supports document.getElementById by doing if(document.getElementById(...)){...}.
Instructions Include all code here. The alert box shows what information can be obtained.
Compatability Works best with Internet Explorer, Firefox, Netscape and Safari. For other browsers it is likely that 'unknown' values will be returned. The most difficult information to obtain is the version number.
Show/hide code Example
<script type="text/javascript">
function BrowserInfo()
/* Get easy-to-understand information about the user's browser.
Returns details as methods of an object named BrowserInfo. A reference
to BrowserInfo is stored in BrowserObj, so to access the info:
BrowserObj.Platform PC | Mac | Unix
BrowserObj.Codebase IE | Gecko
BrowserObj.BrowserName IE | Safari | Firefox | Mozilla
BrowserObj.Version e.g. 5.02
BrowserObj.Vendor Microsoft | Firefox | Apple | Netscape
or something else in navigator.vendor
the value 'unknown' is returned when the the browser does not match
any of those above.
*/
{
/* Get platform: Mac, PC, Unix, unknown */
var Setting = navigator.platform;
if(Setting)
{
if(Setting.search("Mac")!= -1) this.Platform = "Mac";
else
if(Setting.search("Win")!= -1) this.Platform = "PC";
else
if(Setting.search("Unix")!= -1) this.Platform = "Unix";
else this.Platform = "unknown";
}
else /* navigator.platform doesn't store the platform for this browser */
{
this.Platform = "unknown";
}
/* Get codebase */
Setting = navigator.userAgent;
if(Setting.search("MSIE")!= -1) this.Codebase = "IE";
else
if(Setting.search("Gecko")!= -1) this.Codebase = "Gecko";
else this.Codebase = "unknown";
/* Get browser name */
if(Setting.search("Firefox")!= -1) this.BrowserName = "Firefox";
else if(Setting.search("MSIE")!= -1) this.BrowserName = "IE";
else if(Setting.search("Safari")!= -1) this.BrowserName = "Safari";
else if(Setting.search("Mozilla")!= -1) this.BrowserName = "Mozilla";
else this.BrowserName = "unknown";
/* Get browser version */
if(this.BrowserName!="unknown")
{
var pos = Setting.search("rv:");
if(pos!= -1)
{
pos = pos + 3;
var pos2 = (Setting.substr(pos).search("[\)]"));
this.Version = Setting.substr(pos,pos2);
}
else
{
pos = Setting.search(this.BrowserName);
if(pos>-1) pos = (pos+this.BrowserName.length);
this.Version = Setting.substr(pos+1,4);
}
}
else this.Version = "unknown";
/* Get browser maker */
Setting = navigator.vendor;
if(Setting)
{
if(Setting.search("Apple")!= -1) this.Vendor = "Apple";
else this.Vendor = Setting;
}
else
{
Setting = navigator.appName;
if(Setting.search("Microsoft")!= -1) this.Vendor = "Microsoft";
else if(Setting.search("Netscape")!= -1) this.Vendor = "Netscape";
else this.Vendor = "unknown";
}
} /* end of function BrowserInfo */
BrowserInfo.prototype.Platform=null;
BrowserInfo.prototype.Codebase=null;
BrowserInfo.prototype.BrowserName=null;
BrowserInfo.prototype.Version=null;
BrowserInfo.prototype.Vendor=null;
BrowserObj = new BrowserInfo();
alert(BrowserObj.Platform+"\n"+BrowserObj.Codebase+"\n"+BrowserObj.BrowserName+"\n"+BrowserObj.Version+"\nVendor:"+BrowserObj.Vendor)
</script>
NB The navigator.x values for your browser are