Showing posts with label Prototype. Show all posts
Showing posts with label Prototype. Show all posts

Tuesday, July 26, 2011

Chosen

Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors.

https://github.com/harvesthq/chosen/
http://harvesthq.github.com/chosen/ 

Monday, February 7, 2011

JS Libs Deconstructed

The Deconstructed series is designed to visually and interactively deconstruct the internal code of JavaScript libraries, including jQuery, Prototype and MooTools.
It breaks the physical JavaScript into visual blocks that you can easiliy navigate. Each block opens to reveal its internal code. Clickable hyperlinks allow you to follow program flow.

Sunday, April 18, 2010

jStorage - store data locally with JavaScript

JavaScript: The Definitive Guide
jStorage is a simple wrapper plugin for Prototype, MooTools and jQuery to cache data on browser side.
jStorage was first developed under the name of DOMCached but since a lot of features were dropped to make it simpler (like the support for namespaces and such) it was renamed. DOMCached had separate files for working with Prototype and jQuery but jStorage can handle both in one go.
http://www.jstorage.info/

Thursday, February 25, 2010

Ajax.Responders.register

Ajax.Responders.register({
onCreate: function() {
new Effect.Appear('ajax_loader', { duration: 0.3, to: 0.5 });
},
onComplete: function(request, transport, json) {
if (0 == Ajax.activeRequestCount) {
new Effect.Fade('ajax_loader', { duration: 0.3, from: 0.5 });
}
if(!request.success()) {
var errorMapping = $H({
400: ['Bad Request', 'The request contains bad syntax or cannot be fulfilled.'],
401: ['Authorization Required', 'You need to authenticate to access this page.'],
403: ['Forbidden', 'The request was a legal request, but the server is refusing to respond to it.'],
404: ['Page Not Found', 'The requested resource could not be found.'],
405: ['Method Not Allowed', 'A request was made of a resource using a request method not supported by that resource; for example, using GET on a form which requires data to be presented via POST, or using PUT on a read-only resource.'],
406: ['Not Acceptable', 'The action you tried to perform on this resource was considered unacceptable.'],
415: ['Unsupported Media Type', 'The media type you are requesting is unsupported.'],
422: ['Unprocessable Entity', 'The request was well-formed but was unable to be followed due to semantic errors.'],
500: ['Application Error', 'An error occurred in the application code. Report sent.'],
503: ['Service not available', 'The webserver did not respond to the request.'],
505: ['HTTP Version Not Supported', 'The requested version is not available on this server.']
});

var errorMessage = errorMapping.get(transport.status) || ['Unknown Error', 'An error occurred, but could not be determined correctly.'];

if (transport.responseJSON && transport.responseJSON.error)
errorMessage = [transport.responseJSON.error.title, transport.responseJSON.error.message]

var notifyUser = new GrowlNotifier({
title: errorMessage[0],
message: errorMessage[1],
image: "/images/elements/growl_warning.png",
type: 'error'
});
}
}
});
The Window.Growl Script.aculo.us mod is a modified version of Daniel Mota's Window.Growl adapted for the Script.aculo.us framework.
Growl.Smoke({
title: "Growl.Smoke Script.aculo.us mod",
text: "http://blog.var.cc/static/growl/",
image: "image/var-logo-60.png",
duration: 2.0
});
http://blog.var.cc/static/growl/
http://pastie.org/818221

Sunday, January 10, 2010

Protolicious

Protolicious is a set of javascript snippets based on prototype.js (and other random stuff)

Element (Element.Methods) extensions

  • Element#setProperty
  • Element#swapClassName
  • Element#enableClassName
  • Element#contains
  • Element#indexOf
  • Element#isTagName
  • Element#getContentWidth
  • Element#getContentHeight
  • Element#setWidth
  • Element#setHeight
  • Element#appearVisible
  • Element#delegate
  • Element#fillDocument
  • Element#centerInViewport

Function extensions

  • Function.K
  • Function#negate
  • Function#runOnce
  • Function#_new
  • Function#toDelayed
  • Function#toDeferred
  • Function#addAdvice

Array extensions

  • Array#sum
  • Array#namespace

Field (Form.Element.Methods) extensions

  • Field#isBlank
  • Field#present

Form (Form.Methods) extensions

  • Form#unserialize

Event extensions

  • Event.simulate
  • Event.register
  • Event.unregister

Cookie

  • Cookie.set
  • Cookie.get
  • Cookie.unset

Prototype

  • Prototype.addScript
  • Prototype.addStylesheet

Object extensions

  • Object.isEvent
  • Object.methodize
http://github.com/kangax/protolicious

Ajax.JSONRequest is JSONP for Prototype.js

The Basics

Your options are:

  • onCreate: When the request is built but before it is invoked
  • onSuccess: When the request is completed
  • onFailure: When the request times out and fails
  • onComplete: When the request is completed, regardless of success or failure
  • callbackParamName: The name of the callback query parameter to use (defaults to "callback")
  • parameters: Parameters to pass to the request
  • timeout: The seconds before canceling the request and invoking onFailure

Handling response content:

The first (and only) argument passed to your response handlers is a Ajax.JSONResponse object. Access the resulting JSON data via that object's responseJSON property or get at the raw JSON string with that object's responseText property.

new Ajax.JSONRequest('http://api.flickr.com/services/feeds/photos_public.gne', {
callbackParamName: "jsoncallback",
parameters: {
tags: 'cat', tagmode: 'any', format: 'json'
},
onCreate: function(response) {
console.log("1: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("1: success", response, response.responseJSON);
},
onFailure: function(response) {
console.log("1: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("1: complete", response, response.responseJSON);
}
});

Handling Failures

Since there is no way to inspect what happens after we make a request with the JSONP technique, we're stuck having to make informed guesses about what's going on.

This example makes a request to an invalid URL. Since the callback is not invoked within the default timeout period (10 seconds) the request is "cancelled" and the onFailure callback is invoked if specified. The Ajax.JSONResponse will have the status of 504 and statusText of "Gateway Timeout".

new Ajax.JSONRequest('http://api.flickr.com/services/feeds/asdfasdfasdfasdfasdfsdf', {
callbackParamName: "jsoncallback",
parameters: {
tags: 'cat', tagmode: 'any', format: 'json'
},
onCreate: function(response) {
console.log("2: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("2: success", response, response.responseJSON);
},
onFailure: function(response) {
console.log("2: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("2: complete", response, response.responseJSON);
}
});

Using a custom timeout period

You can set your own timeout period. This example sets this timeout to 0.1 seconds which is pretty much guaranteed to fail.

new Ajax.JSONRequest('http://api.flickr.com/services/feeds/photos_public.gne', {

// Short timeout illustrates failure mechanism. This will "fail" because we don't
// get a response in time.
timeout: 0.1,

callbackParamName: "jsoncallback",
parameters: {
tags: 'cat', tagmode: 'any', format: 'json'
},
onCreate: function(response) {
console.log("3: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("3: success", response, response.responseJSON);
},
onFailure: function(response) {
console.log("3: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("3: complete", response, response.responseJSON);
}
});
http://github.com/dandean/Ajax.JSONRequest

Monday, November 9, 2009

Tooltip.js

jQuery:
tip.init(object) #tooltip will be taken from object "helper" attribute
img src="..." helper="..."
tip.init('img[helper]')
var tip = {
init : function(e){
$(e).bind("mouseenter", this.createTip);
$(e).mouseleave(function(){$("#tip").remove()});
$(e).click(function(){$("#tip").remove()});
$(e).mousemove(function(e){$("#tip").css({left:e.pageX+30,
top:e.pageY-16})});
},
createTip : function(e) {
var obj=$(e.currentTarget),
title=$.trim(obj.attr("helper"));
if(title.length>0){
return $("#tip").length === 0 ?
$("<div>").html("<span>"+$.trim(obj.attr("helper"))+"</span>").
attr("id","tip").
css({left:e.pageX+30,
top:e.pageY-16,
position:'absolute',
border:'1px solid #FFE222',
background:'#FFFBC2',
color:'#514721',
padding:'5px 10px',
textTransform:'lowercase',
fontVariant:'small-caps',
zIndex:9000}).
appendTo("body") : null;
} else {return false}
}
};
Prototype:
tip.createTip(container,object) #tooltip will be taken from object "title" attribute
<div id="container">
<img src="..." title="..." />
</div>
tip.createTip($('container'),'img[title]')
var tip = {
title : '',
opacity: .8,
marginX: 30,
marginY: -46,
position : function(i,e){
return i.setStyle({left:e.clientX+this.marginX+'px',
top:e.clientY+this.marginY+'px'})
},
enter : function(i){
var tip=this;
$(i).observe(antHill.events.menter,function(e){
var div,obj=$(e.currentTarget);
tip.title=obj.readAttribute("title");
obj.writeAttribute("title",'');
if($("tip")===null){
div=new Element('div',{id:'tip'});
div.addClassName('tooltip').
setOpacity(tip.opacity).
innerHTML="<span>"+tip.title+"</span>";
tip.position(div,e);
$($$('body')[0]).insert({bottom:div});
}
Event.stop(e)}.bindAsEventListener($(i)));
},
leave : function(i){
$(i).observe(antHill.events.mleave,function(e){
$("tip").remove();
$(i).writeAttribute("title",tip.title);
Event.stop(e)}.bindAsEventListener($(i)));
},
move : function(i){
$(i).observe(antHill.events.mmove,function(e){
antHill.tip.position($("tip"),e);
Event.stop(e)}.bindAsEventListener($(i)));
},
init : function(i){
this.enter(i);
this.leave(i);
this.move(i);
},
createTip : function(c,i){c.select(i).
each(function(i){tip.init(i)})}
};

Sunday, September 13, 2009

LightningDOM

Why on earth would you re-implement the DOM?

And in Javascript?? You’ve got to be out of your minds! Well, it turns out there is actually a sane reason: speed. Most web developers know that the DOM is dog slow, particularly in IE-land. There are plans to fix this in IE8, Chrome and possibly Firefox 3.1, but for at least the next few years, we’ll be supporting browsers with a slow DOM.

But is it really too slow? I mean, can’t users wait a couple seconds for the page to load? After all, they’ve been doing it for years! No, they can’t wait. At least, not anymore. Google taught us the competitive advantage of speed and we’ve been trying (though it’s been tough in Web 2.0 land) to not look back.

http://blog.cornerstonenw.com/2008/09/10/donating-lightningdom/

Wednesday, September 2, 2009

Prototype 1.6.1 released

  • Full compatibility with new browsers. This version of Prototype fully supports versions 1.0 and higher of Google Chrome, and Internet Explorer 8 in both compatibility mode and super-standards mode.

  • Element metadata storage. Easily associate JavaScript key/value pairs with a DOM element. See the blog post that started it off.

  • New mouse events. Internet Explorer’s proprietary “mouseenter” and “mouseleave” events are now available in all browsers.

  • Improved performance and housekeeping. The frequently used Function#bind, String#escapeHTML, and Element#down methods are faster, and Prototype is better at cleaning up after itself.

  • Built with Sprockets. You can now include the Prototype source code repository in your application and use Sprockets for dependency management and distribution.

  • Inline documentation with PDoc. Our API documentation is now stored in the source code with PDoc so it’s easy to send patches or view documentation for a specific version.

http://prototypejs.org/2009/9/1/prototype-1-6-1-released

Friday, June 26, 2009

scripty2

The alpha of scripty2 is out, please head to http://scripty2.com to see the demos and grab a copy.

Also comes with on and offline documentation (probably the most requested feature!), courtesy of http://pdoc.org.

This first release focuses almost exclusively on the complete rewrite of the effects engine, which is now much more flexible and allows for some pretty nifty tricks (but see the demos!).

Note it depends on Prototype 1.6.1_rc3 (a development copy and a minified version are included with the scripty2 download).

Also note that the API is not final yet, and it is not 100% compatible with the old effects API, major changes include:
  • Namespacing: now effects are called in this format: new s2.fx.Morph (...)
  • Reusable effects: need to call .play() on the effects instance, can .cancel() and .finish()
  • Default duration is now 0.2 secs
  • Transitions are much more versatile
If you use effects in the preferred $('element_id').morph() format, this still works and is encouraged.

A more thorough article and tutorial are forthcoming, will post once it's out.

Please discuss this alpha release on the new group: http://groups.google.com/group/scripty2

Tuesday, May 12, 2009

ProColor

ProColor is a simple, flexible, easy-to-use color-picker for the Prototype Javascript framework. ProColor is designed to be friendly to artists and programmers both. This user's manual both documents ProColor and demonstrates it in action.

ProColor is compatible with IE6+, Firefox 2+, Safari 3+, Opera 9+, and Chrome. It is not compatible with very old browsers, but it does at least fall back to a simple text-edit field for old browsers. It runs very well on Safari and Chome, reasonably well on Firefox and Opera, and is usable (if slow) on IE.

http://phantom-inker.livejournal.com/tag/procolor
http://procolor.sourceforge.net/index.php

Monday, May 11, 2009

Using Sizzle with Prototype

Recently, John Resig of jQuery fame released the selector engine used in the new version of jQuery called Sizzle.
Sizzle is a new take on using CSS selectors within Javascript and aims to be far more efficient than the methods commonly used by most current Javascript libraries.
//Overwrite findChildElements to use Sizzle http://sizzlejs.com
Selector.findChildElements = function(element, expression){
expression = expression.join(", ");
var results = Sizzle(expression, element);
if(results.length > 0){
for(var i=0; i < results.length; i++){
results[i] = Element.extend(results[i]);
}
}
return results;
};
http://briancrescimanno.com/2009/03/24/using-sizzle-with-prototype

Tuesday, April 28, 2009

Prototype on Sly is "3x faster"

HTML:
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript" src="Sly.js"></script>

Javascript:
// Overriding CSS Selector Engine.
Sly.handlers = Selector.handlers;
Sly.prototype.findElements = Sly.prototype.search;
Sly.findElement = function(elements, expression, index) {
if (Object.isNumber(expression)) {
index = expression; expression = false;
}
return Sly(expression || '*').filter(elements)[index || 0];
};
Sly.findChildElements = function(element, expressions) {
var result = Sly(expressions.join(',')).search(element);
return Prototype.BrowserFeatures.ElementExtensions ?
result : result.filter(Element.extend);
};
Selector = Sly;
http://slickspeed.firejune.com
http://github.com/digitarald/sly/tree/master

Tuesday, March 17, 2009

motionbox-eventhandler

A prototype-based javascript event bubbling and custom event library. Allows you to subscribe to elements before they exist in the DOM.

The Motionbox EventHandler allows you to:

  • Subscribe to elements before they are on the DOM
  • Subscribe to entire classes of elements (eg. subscribe to clicks on all elements with the class ".foo")
  • Subscribe to arbitrary Objects (including DOMElements) which allows you to nicely separate your code
  • Use the same interface to trigger events between Objects and/or DOM elements
  • Limit your actual observers to a minimum (Only 1 per type of event) and still subscribe many elements
  • Maintain a consistent interface among both custom, browser, and on Object events
  • Easily defer your functions (fire using setTimeout by simply adding { defer: true } to your subscriptions)
  • Blur and focus events are supported and bubble in all the supported browsers.
http://github.com/tobowers/motionbox-eventhandler/tree/master

Mamoo

The Motionbox Advanced Model Observer Observer

A light-weight MVC framework for separating concerns (Data model, views, related actions). It also provides a javscript queue system which lines functions up in an array and will execute them at an interval.

Full documentation can be found here: http://tobowers.github.com/mamoo/

Video demonstration can be found on Motionbox.

It's built on top of Prototype and the Motionbox EventHandler. Minimized it's about 13k.

http://github.com/tobowers/mamoo/tree/master

Thursday, January 29, 2009

Ajax.History

Ajax.History provided features

Three parameters are provided by Ajax.History allowing you to configure the browsing history manager.
A callback has also been introduced: onStateChange(string state).
This callback is launched when the state of the browsing history points to the request.
This allows for example to change the title of the page according to the state (see example below).

Ajax.History.Request

Ajax.History.Request used exactly as Ajax.Request of Prototype.
For an interactive example, we create a simple function:
function ajaxHistoryRequest(url, myState)
{
new Ajax.History.Request(url, {
history : {
id : 'example',
state : myState,
cache : true,
onStateChange: function(state) {
// change title
History.setTitle(History.getTitle() + ' - Page Ajax #' + state);
}
},
onSuccess: function(transport) {
$('box-example').update(transport.responseText);
// some stuff
}
});
ajaxHistoryRequest('history/request1', 'first-test');
ajaxHistoryRequest('history/request2', 'second-test');
ajaxHistoryRequest('history/request3', 'third-test');
** The cache is enabled, if you use a module as FireBug on Firefox, you can see that the use of buttons back/forward of your browser does not reload the Ajax.Request.

Ajax.History.Updater

Ajax.History.Updater used exactly as Ajax.History.Request :
Automatic historyId :
Here, the historyId is not declared, the 'containerName' is used automatically.
new Ajax.History.Updater('containerName', 'my/url/to/load.html', {
history : {
cache : true
}
});

// location.href == '...#containerName={state}'
Disable historyCache :
The cache is disabled, so, when user perform back/forward of browser, the Ajax Request will be loaded whenever.
new Ajax.History.Updater('containerName', 'my/url/to/load.html', {
history : {
id : 'my-own-identifier',
cache : false
}
});

// location.href == '...#my-own-identifier={state}'
Ajax.Cache

How does the cache?
Ajax.Cache can "simulate" an Ajax Request from an Ajax Request made beforehand. It takes only one argument: the object Ajax.Request / Updater create first.
In fact, Ajax.Cache is based on a modified prototype Ajax.Request API. Yes, to simulate the request, I remove the mechanism (real) sending the HTTP request.
Perform simulation manually :
Ajax.Cache is already implemented in Ajax.History.* classes. However, you can use it manually :
// the request is executed firstly
var request = new Ajax.Request('my/url/to/load.html', {
method: 'POST',
...
});

// reproduced the Ajax.Request without HTTP request
new Ajax.Cache(request);
http://www.prototypextensions.com/history

AjaxCSSJS class

AjaxCSSJS is a class for loading JavaScript and CSS files on-demand. (load dynamically)

Download AjaxCSSJS
Example1:
new AjaxCSSJS('layout.css', 'css');


Example2:
new AjaxCSSJS('js/ajaxtab.js', 'js');

Example3:
new AjaxCSSJS('js/ajaxtab.js', 'js',
function() {alert('loaded')}
)

Example4 [New feature: remove()]
var style;

addCss = function() {
style = new AjaxCSSJS('css/style1.css', 'css');
}

removeCss = function() {
style.remove();
}

Tuesday, January 27, 2009

History Manager for AJAX. Fix the back button on AJAX

One of the major issues on AJAX web applications is the accesibility and usability lacks. Many users have manies and don¡t undestands about AJAX, they only expects that if they click the back button then it must works as always and get them back to the previous screen.

Digitarald.de have developed a solution HistoryManager - The Ajax Back-Button (v1.0) for Mootools developers.

Download prototype.historyManager.js

http://www.flash-free.org/en/2008/07/05/history-manager-para-ajax-solucion-al-boton-back

ScrollBox.js

Usage

Simply create a new ScrollBox object and pass in the element you would like to become a scroll box. Note that the element passed used to create the object must be positioned either relative or absolute. The example css file includes this directive on the first line.

Example:
var sb = new ScrollBox($('description_box'));

Full documentation will follow when I have time. For now, there is a complete implementation example included in the zip.

Features

Fully customizable, mostly though simple CSS changes. A sample implementation is included in the download. Supports scrolling with the mouse wheel. The buttons support clicking and holding, the scrollbar has multiple selectable behaviors, and the handle is fully functional. Supports keyboard events up, down, page up, page down, home, and end. Works with named anchors.

http://theblogthatnoonereads.tunasoft.com/2007/04/08/scrollbox_js/

Monday, January 19, 2009

Screencast : How to Create a File Upload Progress Bar in Rails, Passenger, Prototype and Low Pro


How to Create a File Upload Progress Bar in Rails, Passenger, Prototype and Low Pro from Erik Andrejko on Vimeo.

An upload progress bar is one of the best ways to improve the usability of file uploads in your application. This screencast will show how to create a file upload progress bar using Rails, Passenger, Low Pro and the upload progress bar apache module.

Screen Cast

Required

Optional

http://railsillustrated.com/screencast-file-uploads-progress-in-rails-passenger.html