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() { window.open(this.href); 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="http://www.google.com">Google</a> | <a href="http://search.yahoo.com">Yahoo</a> | <a href="http://search.msn.com">MSN</a> | <a href="http://www.ask.com">Ask</a> </div> <p>In a list</p> <ul class="external"> <li><a href="http://www.google.com">Google</a></li> <li><a href="http://search.yahoo.com">Yahoo</a></li> <li><a href="http://search.msn.com">MSN</a></li> <li><a href="http://www.ask.com">Ask</a></li> </ul> <p>Standalone</p> <a href="http://www.google.com" class="external">Google</a> <a href="http://search.yahoo.com" class="external">Yahoo</a> <a href="http://search.msn.com" class="external">MSN</a> <a href="http://www.ask.com" class="external">Ask</a>
jQuery
$(window).bind("load",function() { $(".external a,a.external").bind("click",popup); });
Works as expected in Internet Explorer 6 (Windows 2000), Opera 8.5 and Firefox 1.5.
Prototype
Event.observe(window, 'load', setPopup); function setPopup() { var nodes = $A(document.getElementsByClassName("external")); nodes.each(function(node) { if(node.nodeName == 'A') { Event.observe(node, 'click', popup); } else { var subnodes = $A(node.getElementsByTagName("a")); subnodes.each(function(node) { 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
Summary
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: Web Developer Blog, JavaScript
Comments