JQuery vs Prototype JS

Fri, 15 Apr 2011

This will be a comparison of simple syntax between JQuery vs Prototype JS. I use JQuery at home, and Prototype JS at work. This is a neutral comparison between the two. My favorite things about JQuery is that it's easier and less code, my favorite thing about prototype is that it's not in it's own "Prototype" only object like JQuery is, and Prototype feels more like JavaScript.

Document Loaded

// JQuery
$(document).ready(function() {
	// Code
});
// JQuery Shorthand
$(function() {
	// Code
});
// Prototype
document.observe('dom:loaded', function() {
	// Code
});

Selecting an ID

// JQuery
$("#idname");
// Prototype
$("idname");

Selecting Classes

// JQuery
$(".classname");
// Prototype
$$('.classname');

Select First Class

// JQuery
$(".classname:first-child");
// Prototype
$$('.classname')[0];

Observe an Event on an ID

// JQuery 
$("#item").bind('click', function() {
	// Code
});

// JQuery Shorthand
$("#item").click(function() {
	// Code
});
// Prototype
$("#item").observe('click', function() {
	// code
});

Observe an Event on all Classes

$(".classname").bind('click', function() {
	// code
});

// JQuery Shorthand
$(".classname").click(function() {
	// code
});
// Prototype
$$(".classname").invoke('observe', 'click', function() {
	// code
});

Stopping an Event

// JQuery
$("#id").click(function() {

	//code
	return false;
});
// Prototype
$("id").observe('click', function(e) {
	//code
	Event.stop(e);
});

Handling the Observed Element

// JQuery
$('#idname').click(function() {
	this.hide(); // Hide the item clicked
});
// Prototype
$('idname').observe('click', function(e) {
	el = e.findElement;
	el.hide(); // hide the item clicked
});

Handling Class Names on an ID

// JQuery
$('#id').addClass('red');
$('#id').removeClass('red');
// Prototype
$('id').addClassName('red');
$('id').removeClassName('red');

Handling Class Names on a Class

// JQuery
$('.class').addClass('red');
$('.class').removeClass('red');
// Prototype
$$('.class').invoke('addClassName', 'red');
$$('.class').invoke('removeClassName', 'red');

Ajax GET with JSON

$.get(url, function(data) {
	alert(data.name);
}, 'JSON');
// Prototype
new Ajax.Request(url, {
	method: 'get',
 	onSuccess: function(transport, json) {
		alert(json.name);
      	}
});

As you can see they are extremely similar. These only cover the basics, there is a lot more involved both of them. For example, I prefer Prototypes each loop, but I prefer JQuery's selectors. It's a trade-off, and I don't mind using either. Traversing in both are quite similar, they just use different names.