Monday, March 06, 2006

JavaScript Framework Comparison - Popup Windows

I have a simple function for opening new windows. I want all anchors with the class external (or contained in a parent with this class name) to open links in a new window using this function. So I look at the various frameworks for doing it. In this case, I am comparing jQuery with Prototype (more may follow soon in an edit to this post).

function popup()
 return false;

This function is the same, regardless of framework used (so as to emulate a real world scenario).

HTML code:

<p>In a div</p>
<div class="external">
 <a href="">Google</a> |
 <a href="">Yahoo</a> |
 <a href="">MSN</a> |
 <a href="">Ask</a>
<p>In a list</p>
<ul class="external">
 <li><a href="">Google</a></li>
 <li><a href="">Yahoo</a></li>
 <li><a href="">MSN</a></li>
 <li><a href="">Ask</a></li>
<a href="" class="external">Google</a>
<a href="" class="external">Yahoo</a>
<a href="" class="external">MSN</a>
<a href="" class="external">Ask</a>


 $(".external a,a.external").bind("click",popup);

Works as expected in Internet Explorer 6 (Windows 2000), Opera 8.5 and Firefox 1.5.


Event.observe(window, 'load', setPopup);
function setPopup()
 var nodes = $A(document.getElementsByClassName("external"));
  if(node.nodeName == 'A')
   Event.observe(node, 'click', popup);
   var subnodes = $A(node.getElementsByTagName("a"));
    Event.observe(node, 'click', popup);

It could just be me not knowing enough about Prototype, but that seems like far more code than necessary. It doesn't get any better though. Firefox and Opera opens the new window with the right page as expected, but return false is ignored. Internet Explorer opens a new windows and does not seem to ignore return false, but this.href ends up being undefined


In this case, jQuery wins out. Far less code is needed (both the framework and the page code) and it works in all tested browsers. So it shows that depending on the circumstances, it is not always best to go with the framework with the most features.

Tags: ,

No comments: