Tuesday, January 03, 2006

anchorWrap (JavaScript)

Wraps a node with an anchor (i.e. HyperLink, JavaScript prompt).

// 'node' can be an existing node, or a string (id of node)
// 'anchor' can be a URL string, or a precreated anchor
// 'target' is the target frame to go to, and is optional
function anchorWrap(node,anchor,target)
{
 if(!document.createElement) return;
 var newanchor,parent,sibling;
 if(typeof(node) == "string")
 {
  node = document.getElementById(node);
 }
 if(!node || !node.parentNode) return;
 if(typeof(anchor) == "string")
 {
  newanchor = document.createElement("a");
  newanchor.href = anchor;
 }
 else
 {
  newanchor = anchor;
 }
 if(!newanchor) return;
 // if href is not set (which may be the case when it performs a javascript action), set it to #, so the link is seen
 if(!newanchor.href) newanchor.href = "#";
 // if target is defined, set it
 if(typeof(target) == "string")
 {
  newanchor.target = target;
 }
 // get the sibling and the parent node (so we can insert in the right place)
 sibling = node.nextSibling;
 parent = node.parentNode;
 // add the node to the new anchor
 newanchor.appendChild(node);
 // insert new anchor before sibling, or at the end if there is no sibling
 if(sibling)
 {
  parent.insertBefore(newanchor,sibling);
 }
 else
 {
  parent.appendChild(newanchor);
 }
}

Example uses:

// element with id 'foo', open http://webdevel.blogspot.com in new window
anchorWrap("foo", "http://webdevel.blogspot.com", "_blank");
// element with id 'bar', open http://webdevel.blogspot.com in same window
anchorWrap("bar", "http://webdevel.blogspot.com");
// get element 'baz', style it so it is bold
var baz = document.getElementById("baz");
baz.style.fontWeight = "bold";
// create JavaScript anchor
var jsanchor = document.createElement("a");
jsanchor.onclick = function()
{
 alert("Hello World");
 return false;
}
// wrap 'baz' element with the created JavaScript anchor
anchorWrap(baz, jsanchor);

Tags: ,

No comments: