Wednesday, 1 September 2010

createLink(text, uri, img, alt)

So I've been working on a breadcrumb navigation where I'm using JavaScript to generate a number of CSS styled HTML list elements. Each of these elements are made up of a text element and an image so that in terms of the DOM they look like this:

<li>
  <a href="someUrl.html">
    someText <img src="someImageLocation.png" alt="someAlternativeText"/>
  </a>
</li>

There were 3 of these links and the function was getting longer and longer, so I got to thinking about having to repeat so much redundant code so I pulled the 3 list items out of the function and created another function:

function createLink(text, uri, img, alt){
  var li = document.createElement("li");
  var a = document.createElement("a");
  a.setAttribute("href", uri);
  var liText = document.createTextNode(text);
  var liImg = document.createElement("img");
  liImg.setAttribute("src", img);
  liImg.setAttribute("alt", alt);
  a.appendChild(liImg);
  a.appendChild(document.createTextNode(" "));
  a.appendChild(liText);
  li.appendChild(a);
  return li;
}

Then I called that 3 times thus:

breadCrumb.appendChild(createLink("someText", "someUrl.html", "someImageLocation.png", "someAlternativeText"));

And Bob's your Uncle and Fanny's your...