Archive for the 'prototype' Category

Lazy Load Images with Prototype

Friday, September 7th, 2007

Download lazyload.js.

Requires prototype.js version 1.6.0_rc0 or above.

Element.addMethods({
	lazyload: function(element, options)
	{
		/**
		What does it do?
			It delays loading of images in (long) pages. Images below the fold (far down in the
			page) won’t be loaded before the user scrolls down. This is exact opposite of image
			preloading. With long pages containing heavy image content end user result is the
			same. Page feels snappier. Browser is in ready state after loading visible images.
			No need to wait for n pictures to load.
			
		From Wikipedia:
			Lazy loading is a design pattern commonly used in computer programming to defer
			initialization of an object until the point at which it is needed. It can contribute
			to efficiency in the program’s operation if properly and appropriately used.
		
		Inspired by:
			http://www.appelsiini.net/2007/9/lazy-load-images-jquery-plugin
			
		Requires:
			Prototype.js version 1.6.0_rc0 or later
			A page with lots of big images below the fold (optional)
		*/
		
		function $restore()
		{
			// this function restores the original image source; called when above the fold
			if ( true === $(element).hasAttribute('_src') )
			{
				$(element).writeAttribute({ src: $(element).readAttribute('_src') });
			}
		}
		function $scroll()
		{
			// this function returns the amount the page is scrolled vertically
			var scroll_y = self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			return parseInt(scroll_y);
		}
		function $height()
		{
			// this function returns the height of the viewport
			var window_height = window.innerHeight || document.documentElement.clientHeight;
			return parseInt(window_height);
		}
		var element     = $(element);
		var options     = Object.extend({
			threshold   : 0,
			placeholder : '/images/grey.gif',
			event       : 'scroll',
			frequency   : 0.1
		}, options || {});
 
		var offset      = $(element).cumulativeOffset()[1];
		var activate_on = (offset - options.threshold) - $height();
 
		var old_source  = $(element).readAttribute('src');
		var new_source  = options.placeholder;
 
		$(element)
			.writeAttribute({ src :  new_source })
			.writeAttribute({ '_src' :  old_source });
		
		if ( 'scroll' === options.event )
		{
			new PeriodicalExecuter(function($executor)
			{
				if ( activate_on <= $scroll() )
				{
					$restore(); $executor.stop();
				}
			}, options.frequency);
		}
		else
		{
			$(element).observe(options.event, function(event)
			{
				$restore(); $(element).stopObserving();
			});
		}
 
		return $(element);
	}
});
 
document.observe('contentloaded', function()
{
	$$('img').invoke('lazyload');
});

Equal Height Columns

Tuesday, July 10th, 2007

There are no CSS hacks that can get equal-sized columns, so I wrote this tiny bit of Javascript to do the work for you. Simply add a class of “column” to any <div>s and their heights will match when the page loads.

function matchColumns()
{
	var columns = $A($$('div.column'));
	var column_height = 0;
	var max_height = 0;
	columns.each(function(column)
	{
		column_height = column.getHeight();
		max_height = ( column_height > max_height ) ? column_height : max_height;
	});
 
	columns.each(function(column)
	{
		column.setStyle({
			height: (max_height + 10) + 'px'
		});
	});
}
 
Event.observe(window, 'load', matchColumns);

As always, this script requires prototype, and will work better if you have a DOMReady function instead of window.load.

Smooth Scrolling Links

Saturday, June 23rd, 2007

FAQs are tedious, but we can make their usage much more enjoyable (although I use this word lightly) by imroving the User Experience slightly.

Normal FAQs jump from the list of questions to the answer; with a simple bit of Javascript the page will smoothly scroll to the answer, and then–as a bonus–the answer will flash slightly.

Event.observe(window, 'load', function()
{
   $$('a[href^=#]:not([href=#])').each(function(element)
   {
      element.observe('click', function(event)
      {
         new Effect.ScrollTo(this.hash.substr(1),
         {
            offset: -12
         });
 
         if ( this.hash.substr(1) !== 'top' )
         {
            if ( Prototype.Browser.IE )
            {
               $(this.hash.substr(1)).setStyle({
                  backgroundColor: '#fff'
               });
            }
 
            Effect.Pulsate(this.hash.substr(1),
            {
               from: 0.5,
               pulses: 5
            });
         }
 
         Event.stop(event);
      }.bindAsEventListener(element));
   });
});

This script requires script.aculo.us

coursework: travel site

Monday, March 5th, 2007

Today I presented some coursework to my Multimedia Databases lectured, Dr. Kyberd.

I got an A!

The final part of this coursework is due on Wednesday, so I’d better pull my thumb out and get on with it.

Regular Expression

Thursday, February 22nd, 2007

It’s been a while since I last wrote anything on here — this blog has been abandoned since I went back to uni. — so I thought it best to show you a small part of the work I’ve been doing.

So here it is, the regular expression I have written for tradeswomen.biz:

search.match(/^(?:an?\s)?([A-Za-z\s]+)?\s(?:(?:in|from|near|around|
close to|working in|based in)\s)([A-Za-z0-9\s]+)(?:[.,;]?)$/);

More prototype

Monday, August 21st, 2006

Earlier I wrote about prototype and script.aculo.us. I’ve been using it even more at work, and really, really like it.

Who wants to write

document.getElementById("searchbox");
when you can write
$('searchbox');
And Ajax; how could it be easier to make an Ajax request than
new Ajax.Request()
Exactly, it couldn’t.

Prototype and script.aculo.us

Wednesday, August 16th, 2006

The prototype javascript library is one of the most brilliant, time-saving tools a web developer can use. It’s so easy to use this in conjunction with script.aculo.us to create some user-friendly “drag-and-drog reordering elements with auto-save” to a page.

I’ve used it in a giant database-driven application we’re developing, and it has helped to trim hours of work down to mere minutes.

UPDATE: My new favourite thing!