This page documents useful functionality in the script used throughout this site. Click the green text to see details of each section.
A document container which shows either an ordered or a random sequence of images, changing them either under user control, by clicking, or under timer control.
The container can be <body> or <div> (possibly others though others have not been tested). The slide show displays the images centred and at the maximum size that will fit into the container, preserving aspect ratio. If the show is under timer control, clicking it alternately pauses and continues it, with the title / tooltip / popup changing accordingly to give user feedback.
Here are two examples - the left sequential, the right random - deliberately having slightly different timings to test over time how one or more on the same page interact (the code was written to handle multiple shows on one page, so they shouldn't and don't, but see the following paragraphs).
Pictures obviously consume resources in being loaded and shown - the amount consumed rises with each additional show, and the rate of consumption with the change rate, so the accurate timing of changes will be unavoidably affected by factors such as CPU loading.
Worse, seemingly the only realistic way of getting accurate picture dimensions is wasteful, to preload 'off screen', note them, and then reload 'on screen'! Further, again because there doesn't seem to be another realistic method, the preload uses the onload attribute of a programmatically created img element, but this attribute has been deprecated. Hence, in any given browser, support for SlideShow may end at any time!
anImg | The <img> tag or its ID in which to show the slides. |
---|---|
aPicArr | Array of relative URLs of the images to be shown. |
aURL | The base URL for the pictures, default document.URL. |
interval | Timer interval in ms, default 0 (change under user control by clicking). |
isRandom | Whether to show the pictures randomly, true, or in sequence, default false. |
repeatBlock | When random, the number of intervening images between repeats of any given one (default: if # of pics < 3, then # - 1, else # / 3). |
startIndex | If not random order, index of starting picture, default 0. |
<script>
<!--
/*
Whether the container for the slide show's <img> tag is the <body> or a <div>, it
must be styled with a width and a height so that images can be centred properly.
For the <body>, you're probably going to want to start with the window dimensions
(choose the scale factor sc to avoid unnecessary scroll bars) …
*/
var sc = 0.97;
var ww = window.innerWidth ?
window.innerWidth :
document.documentElement.clientWidth;
var wh = window.innerHeight ?
window.innerHeight :
document.documentElement.clientHeight;
var bwn = Math.round( sc*ww );
var bhn = Math.round( sc*wh );
document.body.style.width = bwn + "px";
document.body.style.height = bhn + "px";
//-->
</script>
<style type="text/css">
<!--
/*
… whereas for a <div>, styles can be applied directly …
*/
.album { width:350px; height:263px; border:2px solid white; padding:0; }
.album img { margin:0; border:0; padding:0; }
-->
</style>
<!--
The Slide Show
==============
Note: Empty image src attributes as given here are not considered best practice …
http://developer.yahoo.com/performance/rules.html#emptysrc
-->
<div class="album">
<img
id="Slide"
alt="Slide Show"
title="Slide Show"
src=""
onkeypress="slideShow.click(event);"
onclick="slideShow.click(event);"
>
</div>
<script>
<!--
var pics = [ "Pic1.jpg", … ];
var interval = 5000;
var slideShow = new SlideShow( "Slide", pics, undefined, interval, true );
//-->
</script>
A document branch or element - some text, a diagram, etc - which can be alternately shown and hidden (toggled) in response to keystrokes or mouse clicks. In principle, any element can be the sensitive element that does the toggling, and any content can be toggled, giving great versatility - this whole page is an example of using ToggleBlocks and lists to implement a collapsible tree. However, here is a simpler first example based on two <span>s (click the green text a couple of times to see what happens):
Here is a technical term (explanation of technical term), which may need further explanation.
This DHTML equivalent of a footnote or technical appendix makes further detail available to those that want it, without swamping those that don't, with the added advantage that it can be read without leaving the main document flow, and consequent need to navigate back to the point of departure.
anElement | Element or its ID which is sensitive to the click or keystroke. |
---|---|
aCompArr | Element or its ID or array of same which is/are to be toggled. |
init | The initial state: true to show, false to hide, default is to leave as specified by HTML. |
The code below is that of the simple example above. In it note the following:
<style type="text/css">
<!--
@media screen
{
/* Toggle styles */
.toggle
{ text-decoration:none; color:#33CC33; }
.toggle:hover, .toggle:active
{ text-decoration:underline; cursor:help; }
.closed > *, .opened > *
{ color:#CCCCCC; }
.closed, .opened, .toggle
{ color:#33CC33; }
}
@media print
{
.toggle
{ color:#000000; text-decoration:none; }
}
-->
</style>
<!--[if (gte IE 5)&(lte IE 7)]>
<style type="text/css">
<!--
@media screen
{
.closed *, .opened *
{ color:#CCCCCC; }
.closed, .opened, .toggle, .toggle *
{ color:#33CC33; }
.toggle, .toggle *
{ text-decoration:underline; cursor:help; }
}
-->
</style>
<![endif]-->
…
<p>
Here is a
<span
id="TB"
onkeypress="tb.toggle(event);"
onclick="tb.toggle(event);"
title="Explanation of technical term"
>technical term</span><span id="TBText"> (explanation of technical term)</span>,
which may need further explanation.
</p>
<script>
<!--
var tb = new ToggleBlock( "TB", "TBText", false );
setClass( "TB", "toggle", true );
//-->
</script>
A document branch, probably in a block level element, which can be toggled in response to a button press. This might be more appropriate than a Toggle Block for blocks of significant size. On this site, it's used to hide blocks of mathematics that the average person may not have the desire or knowledge to follow, but the more adventurous or knowledgeable may wish to see. Here's a trivial example:
ButtonBlock in v2 now works with an <input type="button"> tag as well as a <button> tag.
Heavy mathematics here!
Inherits from ToggleBlock.
aCaption | The button text, which will be combined with 'Hide ' or 'Show ' depending on the state of the block. |
---|---|
aButton | Button element or its ID. |
aCompArr | Element or its ID or array of same which is/are to be toggled. |
init | The initial state: true to show, false to hide, default is to leave as specified by HTML. |
In the code sample below, note the following:
<style type="text/css">
<!--
/* Hides elements in dynamic HTML */
.invis
{ display:none; margin:0; padding:0; line-height:0; }
@media screen
{
.noscreen
{ display:none; margin:0; padding:0; line-height:0; }
}
@media print
{
.noprint
{ display:none; margin:0; padding:0; line-height:0; }
}
-->
</style>
<input
type="button"
value="Hide Maths"
title="Show/hide maths"
id="MathsButton"
onclick="Maths.toggle(event);"
class="noscreen noprint"
>
<div id="MathsText">
<p><em>Heavy mathematics here!</em></p>
</div>
<script>
<!--
var Maths = new ButtonBlock( "Maths", "MathsButton", "MathsText", false );
setClass( "MathsButton", "noscreen", false );
//-->
</script>
A function to find all the elements of (a) certain type(s) (that is, of matching tag name) within a document or document subtree. Here's a demonstration:
aNode | A node or its ID down from which to search. |
---|---|
theTypes | A Regular Expression or String containing one, or array thereof, to match the target tagNames. Case is ignored. |
An array of the found nodes.
<input
type="button"
value="TreeWalk"
title="Click to count the number of heading tags in this document"
onclick="alert(
'There are '
+ TreeWalk(document.body,'h[1-6]').length
+ ' heading tags in this document!'
);"
>
Push a value onto an array only if it doesn't already exist in the array.
thisArr | The array. |
---|---|
newValue | The new value potentially to be pushed. |
fCompare | Optional function to compare the value and an element. |
Delete all elements of an array equalling a comparison value.
thisArr | The array. |
---|---|
oldValue | The old value to be removed. |
fCompare | Optional function to compare the value and an element. |
Delete all duplicate elements from an array. One and one only copy, the one with the lowest index, is kept of each element.
thisArr | The array. |
---|---|
fCompare | Optional function to compare two elements. |
Note for all these functions: They all call compValues to do the comparisons. If the values involved are not primitive types, then the fCompare parameter should be supplied, see the note under compValues for further information. They all return the updated array.
WARNING - Browser sniffing should never be used for anything critical! More reliable methods such as object and function detection should be used in most circumstances, examples of which exist in the script's code for evPrevDeft and evStopProp. However, browser sniffing can be adequate for non-critical use such as minor styling adjustments.
Because it is not intended to be used in critical situations, no attempt is made to detect 'spoofing' other than can be accomplished by searching the navigator.userAgent property. Note that a few of the more obscure browsers did not visit this site during testing, and so have not been tested.
As the script loads, it creates an object __br (two leading underscores) with the following properties:
n | A two letter designation of the browser (String). |
---|---|
v | The major version number (Number). |
Click to check what the script thinks your browser is:
The values of n are as follows:
n | Browser Name |
---|---|
Ca | Camino |
Ch | Chrome |
FF | Firefox |
Ge | Gecko |
iC | iCab |
IE | Internet Explorer |
KH | KHTML |
Ko | Konqueror |
Mo | Mozilla |
NS | Netscape |
Op | Opera |
OW | OmniWeb |
Sa | Safari |
Sm | Safari Mobile |
WK | Apple Web Kit |
XX | Undetected |
As of v2.2, the v field really is a number, and Opera versions above 9 are discriminated.
An undefined value is always less than a defined one, and two undefined ones are equal.
one | The first value. |
---|---|
two | The second value. |
fCompare | Optional function to compare non-primitive types. |
1 | one > two |
---|---|
0 | one == two |
-1 | one < two |
Note: If the values involved are not primitive types, then the parameter fCompare should be supplied, otherwise comparisons will be between data handles / pointers, and, depending on the script engine or browser, may return a meaningless value or one that is unintended. The function should return the same values as above.
Provide a DOCTYPE for use in child windows. Try to determine if the document has a DOCTYPE declaration (non-IE) and if so create a text copy from the DOM's record of it, otherwise (IE) provide a safe default.
As the script loads, it creates an object __dt (two leading underscores) with the following properties:
d | A recreation of the original DOCTYPE declaration. |
---|---|
x | true if the document is XHTML, otherwise false. |
Click to check what the script thinks this document's DOCTYPE is:
All these function take a single parameter of the event object to be stopped.
Prevent the event's default action.
Prevent further propagation of the event up through the DOM.
Both the above, returns false. This function was previously called stopProp.
This function partially overcomes the lack of browser support for CSS @media print, particularly for page-break-inside:avoid;, by copying a node to another window for printing on its own. Thus it can be used to ensure that large items - such as forms, lists, and images - have the maximum chance of being printable unbroken on a single page.
The new window will have access to the parent document's first stylesheet if it is linked, that is if it is loaded from file not inline, so it is important to ensure that any styles required for printing the node are in the first linked sheet, and that no inline styles precede its loading.
Beware of including <script> tags in the node to be printed. Remember they will not have access to the parent window's DOM, scripts, data, etc.
oElement | A node or its ID which to print. |
---|---|
aHeadings | An array of up to six headings which will be printed with the corresponding numbered <h?> tags. The first three will also be used to make up the temporary document's title. |
<input
type="button"
value="Print this item"
title="Click to print only this item"
onclick="printNode(
'PrintN',
[
'JavaScript Extras v2',
'New, or newly documented, in this version',
'Print Node'
]
);"
class="noprint"
>
Toggle a class being defined on an element - if the class is not present in the displayClass property, it is added, if it is already present, it is removed.
anElement | The DOM element or its id. |
---|---|
aClass | The CSS class (String). |
Sets or unsets a class being defined on an element - if set is true, the class is added to the displayClass property, if set is false or absent, then the class is removed.
anElement | The DOM element or its id. |
---|---|
aClass | The CSS class (String). |
set | Whether to add or remove the class (Boolean). |
Shows or hides the element - if the show parameter is true, the invis class is removed from the element, so displaying it, and vice versa. Calls setClass().
anElement | The DOM element or its id. |
---|---|
show | Whether to show or hide (Boolean). |
Requires the following style definition:
<style type="text/css">
<!--
/* Hides elements in dynamic HTML */
.invis { display:none; margin:0; padding:0; line-height:0; }
-->
</style>
WARNING - May corrupt CSS in IE6 without giving any indication of error! Returns an array of style rule objects whose selectors match that or those given.
selectors | A Regular Expression or String containing one, or array thereof, to match style selector strings. |
---|---|
styleSheets | Optional style sheet or array of them to search - default is all the document's sheets. |
Determine whether a URL is local to the computer or the LAN. Tests for <drive>:, file://, http://localhost/, & http://<IPv4 Address>/. Note that IP tests only check for a pattern of 4 decimal numbers separated by dots, and the minimum beyond this to determine a return value, not that an IP as a whole is valid.
true or false.
aURL | The URL (String). |
---|---|
incLL | Include 'Link Local' IPs 169.254.0.0/16 (Boolean). |
incLAN | Include LAN IPs 192.168.0.0/16, 172.16.0.0/12, & 10.0.0.0/8 (Boolean). |
Remove the anchor and search portions of a URL, and get it into a standard form, with www inserted if requested and appropriate, and for local URLs back slashes replaced by forward, and Windows drive letters preceded by an extra slash. This function was previously called cleanURL.
aURL | The URL (String). |
---|---|
www | Whether to insert www where appropriate (Boolean). |
The cleaned up URL.
Convert a given absolute URL into a relative one, given a base URL. Since HTML5 deprecates ./ URL prefixes, this function was altered in v2.4 to return relative URLs without. In v1, this function was called relURL.
aURL | The absolute URL (String). |
---|---|
aBase | The base URL (String). |
The relative URL.
Return a random integer between 0 & N (inclusive).
N | The maximum value to be allowed as a return |
---|
The random number.
Pads a number with leading zeros, useful for dates and times, National Grid references, etc.
width | The number of digits required, preceding a decimal point if present |
---|
The number padded to the correct width.
Removes leading and trailing spaces from a String.
The trimmed string.
To download the script to your PC, <Right-Click> General.js and choose Save As.
If you absolutely must have the previous version, it's still available from the previous version of this page: Generalv1.html.
Updated | Description |
---|---|
30/12/2021 | v2.6 - Added extra parameter to and general update of SlideShow. |
20/04/2014 | v2.4 - Altered URLRel function to allow for deprecation of ./<etc> in HTML5 |
04/03/2014 | v2.3 - Make Browser Sniffer recognise IE11+ |
05/09/2010 | v2.2 - Improvements to Browser Sniffer. |
13/06/2010 | v2.1 - Safer Array for() loops if the Array.prototype is altered. Better Chrome detection by Browser Sniffer. |
30/04/2010 | Created v2 documenting new or further functionality. |
12/02/2010 | Corrected missing dots (periods, full-stops) in some style listings. |
09/12/2009 | Created v1. |