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!)

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

technorati multi-word tagging bookmarklet : my custom modification

// Replace BLOGNAME with your own blog name. If input is "javascript, text snippets, code" without quotes, output is "Tags: t javascript, t text snippets, t code, t BLOGNAME" with appropriate technorati tag links. span class is tectag. To find posts tagged javascript and code in your Blogger blog, search for ("t javascript" AND "t code") without paranthesis from the Blogger search box at the top, or search for (tag:javascript tag:code) from Technorati.
// This is a compressed and modified version of the bookmarklet code at http://consumingexperience.blogspot.com/2005/07/technorati-tag-creator-for-multiple.html

javascript:(
function(){
var a=' Tags: ';
var t=prompt('enter:','')+', BLOGNAME';
var tr=t.split(',');
for(var i=0;i<tr.length;i++){
        if(i>0){a+=', ';}
        tr[i]=tr[i].replace(/^\s*|\s*$/g,'');
        a+='t '+tr[i].replace(/\s/g,'+')+'\" rel=\"tag\">'+tr[i]+'';
}
prompt('copy:',a+'');
}
)()

Text field's default text

Show a default text...

<script language="javascript">
        function showtxt(thisfield, defaulttxt) {
                thisfield.style.backgroundColor = '#FFFF88';
                if (thisfield.value == defaulttxt) {
                        thisfield.style.color = "#000";
                        thisfield.value = "";
                }
        } 
        function hidetxt(thisfield, defaulttxt) {
                thisfield.style.backgroundColor = '#FFFFFF';
                if (thisfield.value == "") {
                        thisfield.style.color = "#999";
                        thisfield.value = defaulttxt;
                }
        }
script>

...
<input 
  type="text" 
  name="query" 
  onclick="showtxt(this, 'Recherchez ici...')" 
  onblur="hidetxt(this, 'Recherchez ici...')" 
  style="color:#"query"])) { echo "000"; } else { echo "999"; } ?>;" 
  value=""query"])) { echo preg_replace("/[\\\\]+/", "", trim(htmlentities($_POST["query"]))); } else { echo "Recherchez ici..."; } ?>"
>

Javascript clear and recall default form value

// Swap out default text in a form field on click, and recall if field is empty

<script type="text/javascript">
function clickclear(thisfield, defaulttext, color) {
        if (thisfield.value == defaulttext) {
                thisfield.value = "";
                if (!color) {
                        color = "000000";
                }
                thisfield.style.color = "#" + color;
        }
}
function clickrecall(thisfield, defaulttext, color) {
        if (thisfield.value == "") {
                thisfield.value = defaulttext;
                if (!color) {
                        color = "cccccc";
                }
                thisfield.style.color = "#" + color;
        }
}
script>

Javascript clear and recall default form value

// Swap out default text in a form field on click, and recall if field is empty
// Example:

<script type="text/javascript">
function clickclear(thisfield, defaulttext, color) {
        if (thisfield.value == defaulttext) {
                thisfield.value = "";
                if (!color) {
                        color = "000000";
                }
                thisfield.style.color = "#" + color;
        }
}
function clickrecall(thisfield, defaulttext, color) {
        if (thisfield.value == "") {
                thisfield.value = defaulttext;
                if (!color) {
                        color = "cccccc";
                }
                thisfield.style.color = "#" + color;
        }
}
script>

Javascript clear and recall default form value

// Swap out default text in a form field on click, and recall if field is empty
// Example:

<script type="text/javascript">
function clickclear(thisfield, defaulttext, color) {
        if (thisfield.value == defaulttext) {
                thisfield.value = "";
                if (!color) {
                        color = "000000";
                }
                thisfield.style.color = "#" + color;
        }
}
function clickrecall(thisfield, defaulttext, color) {
        if (thisfield.value == "") {
                thisfield.value = defaulttext;
                if (!color) {
                        color = "cccccc";
                }
                thisfield.style.color = "#" + color;
        }
}
script>

popup window

onclick="window.open('index.php', 'blank', 'width=560, height=400, resizable=yes')

javascript redirect

<script language="javascript">window.location="index.php"script>

or

onclick="window.location='index.php?item=' + document.myform.item.value"

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;
}

Javascript Popup Function

// javascript popup

function popUp(url,added) {
                
        menubar = "no";
        if (added == "nav") {menubar = "yes";}

        if (typeof(popupWin) != "object"){
                popupWin = window.open(url,"gmail" , "height=400,width=600,toolbar=" + menubar + ",scrollbars=yes,personalbar=yes,resizable=yes,location=0,statusbar=yes,menubar=0");
        } else {
        if (!popupWin.closed){
                popupWin.location.href = url;
        } else {
                popupWin = window.open(url, "gmail" , "height=400,width=600,toolbar=" + menubar + ",scrollbars=yes,personalbar=yes,resizable=yes,location=0,statusbar=yes,menubar=0");
        }
        }
        popupWin.focus();
        return false;
}

Simple DIV Toggle Javascript

// description of your code here

function simpletogglediv(whichLayer)
{
         var theElementStyle = document.getElementById(whichLayer); 

        if(theElementStyle.style.display == "block")
        { 
                theElementStyle.style.display = "none";  
                 
        }
        else
        { 
                theElementStyle.style.display = "block"; 
        }
} 

Fireworks Javascript image functions

// rollover, swap, etc.

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
} 
 

Javascript optimisation - while

Using as a benchmark the task of iterating over a live collection produced by getElementsByTagName. IE/Win, Gecko and Safari all agree as to the fastest means:

var i = 0, el, els = document.getElementsByTagName(nodeName);
while (el = els[i++]) {
    // [...]
}


Using a while loop and storing the live collection in a variable is the quickest technique in all of these browsers.

Using FlashObject and the miniFLV player to play videos from an entry

Ideally, at some point, I'll modify the plug-in for EE that shows Flash objects to use flashobject.js.

This code assumes custom fields in the blog.

FlashObject: http://blog.deconcept.com/flashobject/
MiniFLV: http://www.richnetapps.com/miniflv.htm

Online Example.

{if project_video}
{if project_video_title}<h4>{project_video_title}: Video Cliph4>{/if}

<div id="videoClip">
<p style="margin: 10px 0; padding: 10px; border: 3px solid red;"><a href="http://www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank" title="Get Flash Player"><img src="http://www.macromedia.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Flash Player" height="31" width="88" align="left" style="padding-right: 10px">a>Flash 7 or above and JavaScript are required to view the project video clip. Please download the //www.macromedia.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank" title="Get Flash Player">latest Flash plug-in.

{if project_video_alt}

{project_video_alt}

{/if}
{/if}
« Newer Snippets
Older Snippets »
34 total  XML / RSS feed