4umi.com/web/javascript/snips

Bits and pieces

Basic Javascript

This page serves as a collection of often used code components, common variables, and various small functions. They should be mostly self-explicatory to scripters on an intermediate level. A legend of the colours used follows.

Variables

Searchstring to array

function searchurl() { if(window.location.search) {
  var u, n = window.location.search.substring(1).split(/&/), i = n.length;
  while( i-- ) {
    n[i] = n[i].split( /=/ );
    u[n[i][0]] = n[i][1];
  }
  return u;
}}
// var s=searchurl(); if( s['lang']==='en' ) { ... }

Arrays

var numbers = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen' ];
var days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ];
var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];
var signs = [ 'Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces' ];

Strings

var whitespace = new String(' \t\n\r\f');

Numbers

function leadzero(n) { return ( n < 10 ? '0' : '' ) + n; }
function tailzero(n) { n = Math.round( n * 10 ) / 10; return n + ( n===Math.round( n ) ? '.0' : '' ); }
function minsec(s) { m = Math.floor( s / 60 ); s -= 60 * m; return m + ':' + leadzero( s ); }

Unicodes

document.write( 'The Chinese character for "love": ' + ' \u7231'.big().big().bold() );

Dynamic

Dynamic divisons

Assume a stylesheet contains a rule like this:

.hid { display: none; }

Then an element o can easily be toggled in and out of view by removing or adding the name of “hid” to its applied classes like so:

function toggle( o ) {
 o.className = /\bhid\b/.test( o.className ) ?
  o.className.replace( /(\s*)\bhid\b(\s*)/, '$1$2' ) :
  o.className + ' hid';
 return false;  //  if from a link, don't follow the href
}

Windows

Centered pop-up

function pop( url, w, h ) {
 w = w || 250;
 h = h || 100;
 var win = window.open( url, '_pop',
  'width=' + w + ',height=' + h +
  ',left=' + Math.round( ( window.screen.AvailWidth - w ) / 2 ) +
  ',top=' + Math.round( ( window.screen.AvailHeight - h ) / 2 ) +
  ',dependent,directories,location,menubar,resizable,scrollbars,status,toolbar' );
 if( win ) {
  win.focus();
 } else if( window.confirm( 'A pop-up was blocked.\nThe page can be opened in this window instead.' ) ) {
  window.location.href = url;
 }
}
// something.onclick = pop( 'somefile.html', 400, 200 );

Pop up the window

var w = window.open(), d = w.document;
d.open();
d.write( window.document.documentElement.outerHTML );
d.close();

Frames

Framebuster

// straight after the <head> opening tag
if( top !== self ) { top.location.replace( self.location.href ); }

Framerelocator

// in each page, somewhere after the <body> opening tag
if( top===self || top.location.hostname !== 'www.mydomain.com' )
  document.write( '<a href="http://www.mydomain.com/frame.html?' + location.href + '">' +
    'View this page in its ' + ( top == self ? '' : 'own ' ) + 'frames</a>.' );

// in the frameset, do not omit <noscript><frame src="default.html"></noscript>
document.write( '<frame src="' + ( location.search.substring(1) || 'default.html' ) + '">' );

Events

Order of events

Even where accepted specifications leave no room in their wording for deviating interpretations, deviations among browsers are the necessary rule rather than the equally necessary exception. So what can we expect on topics about which the specification is silent?

<input
 onblur="alert( 'Happens first in Netscape 6 and Notes/Domino 6.' );"
 onchange="alert( 'Fires first in IE6, Netscape 4 and Opera 5.' );"
>

The lesson at the bottomline is perhaps to expect the widest deviations possible on the internet, and design scripts along the straight and narrow. If it is at all possible to question a specification, then surely one day one browser will do exactly that.

Image swap

Less is more.

function swap( x, s ) { if( document.images ) { document.images[x].src = s; } }

Disable selections

function disable( e ) { return false; }
function enable( e ) { return true; }
document.onselectstart = disable; // if IE4+
if( window.sidebar ) { document.onmousedown = disable; document.onclick = enable; } // if NS6
// or per element : <p unselectable="on"><p>  // in IE

IE-only

Open Word

Commonly, Word documents (with the .doc extension) linked to from a webpage open directly in Internet Explorer, as it is commonly equipped with a plug-in add-on for the application. However, a document sent with a mime-type of application/octet-stream will always be opened external of the browser. With application/msword, it may or may not, depending on the setting of ToolsFolder OptionsFile Types → '.doc' → Advanced → 'Browse in Same Window' (in at least XP).

To launch the real thing from clientside script, …

<a href="http://www.example.com/filename.doc" onclick="openWord( this.href );return false">Word document</a>

… requires an ActiveXObject:

function openWord( file ) {
 var oword = new ActiveXObject( 'Word.Application' );
 if( oword!==null ) {
   oword.Visible = true;
   oword.Documents.Open( file );
 }
}

… or the CreateObject function in VBScript:

<script type="text/vbscript">
Sub openWord( file ) 
  Dim oword 
  Set oword = CreateObject( 'Word.Application' ) 
  oword.Visible = true 
  oword.Documents.Open file 
  oword.Activate 
End Sub
</script>

Copy something

Usually when something must be copied, I doubleclick the element and hit Ctrl+C. It is quick and it is sure to copy exactly what I just selected (often including invisible content). A button to encourage users to make a copy of something, is however present on many sites, as if it were itself content.

// Requires a <textarea id="TA" style="display:none;"></textarea> in the body.
// Will copy the text of the element with the given ID, or the selection if there is one.
// IE4+. To read the clipboard, use window.clipboardData.getData( 'Text' );
function copy2clipboard( id ) {
 document.all.TA.innerText = ( isselect() || document.all[id] && document.all[id].innerText || '' );
 document.all.TA.innerText += '\n -- Brought to you by XYZ. --';
 var r = document.all.TA.createTextRange();
 r.execCommand( 'RemoveFormat' );
 r.execCommand( 'Copy' );
}

// Return the selected text, if any, cross-browser
function isselect() {
 var d=document;
 if( d.getSelection ) { return d.getSelection(); }
 if( d.selection && d.selection.createRange ) { return d.selection.createRange().text; }
 return '';
}

// HTML might look like:
//<input type="button" value="Copy me!" onclick="copy2clipboard( id );">

Situations where a button is appropriate, are thinkable. Teaching users the contextmenu and shortcut keys is however more effective and more sensible in the long run. What matters is usually a message, not the details of how it is delivered.

or