Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

About this user

Brent http://brentg.org

« Newer Snippets
Older Snippets »
8 total  XML / RSS feed 

Insert After

/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
parent.insertBefore(node, referenceNode.nextSibling);
}

addEvent

/* addEvent: simplified event attachment */
function addEvent( obj, type, fn ) {
if (obj.addEventListener) {
obj.addEventListener( type, fn, false );
EventCache.add(obj, type, fn);
}
else if (obj.attachEvent) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
obj.attachEvent( "on"+type, obj[type+fn] );
EventCache.add(obj, type, fn);
}
else {
obj["on"+type] = obj["e"+type+fn];
}
}

PLinks (Purple numbers)

function plinkHighlight() {
if (/#p-/.test(document.location)) {
// The user arrived via a plink
var plink_id = document.location.href.split('#')[1];
var para = document.getElementById(plink_id);
para.className = para.className + ' plinkHighlight';
}
}

function addpLinks() {
if (!/archive/.test(document.location.href)) {
return; /* Only show plinks on story pages */
}
var paras = document.getElementsByTagName('p');
for (var i = 0; i < paras.length; i++) {
var current = paras[i];
if (/^p-/.test(current.id)) {
// It's a purple link paragraph
var plink = document.createElement('a');
plink.href = document.location.href.split('#')[0] + '#' + current.id;
plink.className = 'plink';
plink.appendChild(document.createTextNode(' #'));
current.appendChild(plink);
}
}
}

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}

addLoadEvent(addpLinks);
addLoadEvent(plinkHighlight);

Form Validation - Generic

window.onload = initialise;

function initialise()
{
var objForms = document.getElementsByTagName('form');

// Attach an event handler for each form
for (var iCounter=0; iCounter objForms[iCounter].onsubmit= function(){return validateForm(this);}
}


// Event handler for the form
function validateForm(objForm)
{
var arClass = new Array();
var iErrors = 0;
var objField = objForm.getElementsByTagName('input');
var objLabel = objForm.getElementsByTagName('label');
var objList = document.createElement('ul');

// Get the id or name of the form, to make a unique
// fragment identifier
if (objForm.id)
var strLinkID = objForm.id + 'ErrorID';
else
var strLinkID = objForm.name + 'ErrorID';

// Iterate through input form controls, looking for validation classes
for (var iFieldCounter=0; iFieldCounter {
// Get the class for the field, and look for the appropriate class
arClass = objField[iFieldCounter].className.split(' ');
for (var iClassCounter=0; iClassCounter {
switch (arClass[iClassCounter])
{
case 'string':
if (!isString(objField[iFieldCounter].value, arClass))
{
if (iErrors == 0)
logError(objField[iFieldCounter], objLabel, objList, strLinkID);
else
logError(objField[iFieldCounter], objLabel, objList, '');
iErrors++;
}
break;
case 'number':
if (!isNumber(objField[iFieldCounter].value, arClass))
{
if (iErrors == 0)
logError(objField[iFieldCounter], objLabel, objList, strLinkID);
else
logError(objField[iFieldCounter], objLabel, objList, '');
iErrors++;
}
break;

case 'email' :
if (!isEmail(objField[iFieldCounter].value, arClass))
{
if (iErrors == 0)
logError(objField[iFieldCounter], objLabel, objList, strLinkID);
else
logError(objField[iFieldCounter], objLabel, objList, '');
iErrors++;
}
break;
}
}
}

if (iErrors > 0)
{
// If not valid, display error messages
var objError = objForm.getElementsByTagName('div');

// Look for existing errors
for (var iCounter=0; iCounter if (objError[iCounter].className == 'validationerrors')
var objExisting = objError[iCounter];

var objNew = document.createElement('div');
var objTitle = document.createElement('h2');
var objParagraph = document.createElement('p');
var objAnchor = document.createElement('a');

if (iErrors == 1)
objAnchor.appendChild(document.createTextNode('1 Error in Submission'));
else
objAnchor.appendChild(document.createTextNode(iErrors + ' Errors in Submission'));
objAnchor.href = '#' + strLinkID;
objAnchor.className = 'submissionerror';

objTitle.appendChild(objAnchor);
objParagraph.appendChild(document.createTextNode('Please review the following'));
objNew.className = 'validationerrors';

objNew.appendChild(objTitle);
objNew.appendChild(objParagraph);
objNew.appendChild(objList);

// If there were existing error, replace them with the new lot,
// otherwise add the new errors to the start of the form
if (objExisting)
objExisting.parentNode.replaceChild(objNew, objExisting);
else
{
var objPosition = objForm.firstChild;
objForm.insertBefore(objNew, objPosition);
}

objAnchor.focus();

// Don't submit the form
objForm.submitAllowed = false;
return false;
}

// Submit the form
return true;
}

// Function to add a link in a list item that points to problematic field control
function addError(objList, strError, strID, strErrorID)
{
var objListItem = document.createElement('li');
var objAnchor = document.createElement('a');

// Fragment identifier to the form control
objAnchor.href='#' + strID;

// Make this the target for the error heading
if (strErrorID.length > 0)
objAnchor.id = strErrorID;

// Use the label prompt for the error message
objAnchor.appendChild(document.createTextNode(strError));
// Add keyboard and mouse events to set focus to the form control
objAnchor.onclick = function(event){return focusFormField(this, event);}
objAnchor.onkeypress = function(event){return focusFormField(this, event);}
objListItem.appendChild(objAnchor);
objList.appendChild(objListItem);
}

function focusFormField(objAnchor, objEvent)
{
// Allow keyboard navigation over links
if (objEvent && objEvent.type == 'keypress')
if (objEvent.keyCode != 13 && objEvent.keyCode != 32)
return true;

// set focus to the form control
var strFormField = objAnchor.href.match(/[^#]\w*$/);
var objForm = getForm(strFormField);
objForm[strFormField].focus();
return false;
}

// Function to return the form element from a given form field name
function getForm(strField)
{
var objElement = document.getElementById(strField);

// Find the appropriate form
do
{
objElement = objElement.parentNode;
} while (!objElement.tagName.match(/form/i) && objElement.parentNode);

return objElement;
}

// Function to log the error in a list
function logError(objField, objLabel, objList, strErrorID)
{
// Search the label for the error prompt
for (var iCounter=0; iCounter if (objLabel[iCounter].htmlFor == objField.id)
var strError = objLabel[iCounter].firstChild.nodeValue;

addError(objList, strError, objField.id, strErrorID);
}

// Validation routines - add as required

function isString(strValue, arClass)
{
var bValid = (typeof strValue == 'string' && strValue.replace(/^\s*|\s*$/g, '') != '' && isNaN(strValue));

return checkOptional(bValid, strValue, arClass);
}

function isEmail(strValue, arClass)
{
var objRE = /^[\w-\.\']{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,}$/;
var bValid = objRE.test(strValue);

return checkOptional(bValid, strValue, arClass);
}

function isNumber(strValue, arClass)
{
var bValid = (!isNaN(strValue) && strValue.replace(/^\s*|\s*$/g, '') != '');

return checkOptional(bValid, strValue, arClass);
}

function checkOptional(bValid, strValue, arClass)
{
var bOptional = false;

// Check if optional
for (var iCounter=0; iCounter if (arClass[iCounter] == 'optional')
bOptional = true;

if (bOptional)
if (strValue.replace(/^\s*|\s*$/g, '') == '')
return true;
else
return bValid;

return bValid;
}

New Window (unobtrusive _blank with DOM)

/* This handy function from Simon Willison allows you to stack up 'window.onload' events

without them stepping on each other's toes. It's explained here - http://www.sitepoint.com/blog-post-view.php?id=171578 */

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}


/* This is our old popup code - parts of the site still use it, so I need to keep it */
function acpopup(strURL,strType,strHeight,strWidth) {
var strOptions="";
if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
window.open(strURL, '', strOptions);
}


/* new accessible, unobtrusive popup code */

function windowLinks() {
if(!document.getElementsByTagName) {
return;
}

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
var anchor = anchors[i];
var relIndex = anchor.rel;
if (relIndex){
var relSplit = relIndex.split("|");
/* XHTML compliant target attribute */
if (relSplit[0] == "external") {
anchor.target = "_blank";
anchor.className = "external";
anchor.title = "Load in new window: "+ anchor.href;
/* XHTML compliant popup attribute */
} else if (relSplit[0] == "popup") {
anchor.className = "popup";
anchor.title = "Link loads in Popup Window";
anchor.popupWidth = relSplit[1];
anchor.popupHeight = relSplit[2];
anchor.onclick = function() {acpopup(this.href,'console',this.popupWidth,this.popupHeight);return false;};
}
}
}
}

addLoadEvent(function() {
windowLinks();
//otherFunctions();
//goHere();
});

Alternate table / list item rows

window.onload = colorRows;
function colorRows() {
var myTR = document.getElementsByTagName('tr');
for (var i=0;i if (i%2) {
myTR[i].className = 'rowTint';
}
}
}

Collapsable Navigation Menu

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">







Example 2










Toggle Show/Hide

function toggleAnswer(ul_id) {
var u = document.getElementById(ul_id);

if(u.className == "hiddenAnswer") {
u.className = null;
} else {
u.className = "hiddenAnswer";
}
}

// then create a css class like so...

.hiddenAnswer {
display: none;
}
« Newer Snippets
Older Snippets »
8 total  XML / RSS feed