Tag Archives: mootools

Mootools Gallery ZoomBox Plugin

I needed a simple lightweight Mootools Gallery Lightbox, and after a few googles, I found nothing that suited my needs with out all the extra ‘captions’ and grouping and bloat.

This is a simple zoom from start position type lightbox that uses only the Mootools Core version 1.2.4 at this time but should work with 1.3.x

I have used it on the Glass Effects web page which you can view for a demo.

You will notice on my class, I am adding a CSS class ‘shadow’ to the large image, this is used for basic styling and you can do any CSS you want to it. ( or none at all )

Here is how it is built up;

HTML:

< div id="photos">
	< ul>
		< li>< a href="http://www.glasseffects.co.nz/assets/volume1/2_large.jpg" class="zoomBox" title="Glass Effects - Painted toi toi image on glass splashback">< img src="http://www.glasseffects.co.nz/assets/volume1/2_small.jpg" alt="Glass Effects - Painted toi toi image on glass splashback" />< /a>< /li>
		< li>< a href="http://www.glasseffects.co.nz/assets/volume1/3_large.jpg" class="zoomBox" title="Glass Effects - Uniformed lines on Effects glass splashback">< img src="http://www.glasseffects.co.nz/assets/volume1/3_small.jpg" alt="Glass Effects - Uniformed lines on Effects glass splashback" />< /a>< /li>
		< li>< a href="http://www.glasseffects.co.nz/assets/volume1/5_large.jpg" class="zoomBox" title="Glass Effects - Textured Effect splashback using GlassArt colour #25 Iridium">< img src="http://www.glasseffects.co.nz/assets/volume1/5_small.jpg" alt="Glass Effects - Textured Effect splashback using GlassArt colour #25 Iridium" />< /a>< li>
		< li>< a href="http://www.glasseffects.co.nz/assets/volume1/6_large.jpg" class="zoomBox" title="Glass Effects - Stencilled Effect – toi toi. GJ Gardner Show Home, Tauranga">< img src="http://www.glasseffects.co.nz/assets/volume1/6_small.jpg" alt="Glass Effects - Stencilled Effect – toi toi. GJ Gardner Show Home, Tauranga" />< /a>< /li>
		< li>< a href="http://www.glasseffects.co.nz/assets/volume1/7_large.jpg" class="zoomBox" title="Glass Effects - Painted glass for bar. GlassArt colour #49 Red Red Red">< img src="http://www.glasseffects.co.nz/assets/volume1/7_small.jpg" alt="Glass Effects - Painted glass for bar. GlassArt colour #49 Red Red Red" />< /a>< /li>
	< /ul>
< /div>

JS ( In Page ):


window.addEvent('domready', function() {

	/* Any other JS needed for your page */
	
	var myZoomBox = new zoomBox();


	/* to set options */
	
	var myZoomBox = new zoomBox({
		zb_class:     '.mootools-ftw',
		zb_element:   'big_image',
		zb_loader:    './loading.gif'
	});

});

ZoomBox Class:

// Create the Mootools ZoomBox Class
var zoomBox = new Class({
	
	Implements : Options,
	// Editable Settings
    options: {
		zb_class:     '.zoomBox',                    // class of anchors/images to find on page.
		zb_element:   'zb_image',                    // id of zppmBox pop-up div
		zb_loader:    '/assets/images/loading.gif',  // path to loading image
		scale_image:  true,                          // scale large image if it is bigger than our screen size, bool true/false
		win_width:    1024,                          // basic window width, ignore
		win_height:   768                            // basic window height, ignore
    },

	initialize: function(options){
		// set options and internal settings
		this.setOptions(options);
		this.setWindowSize();
		this.currentIndex;
		this.images = new Array();
		this.positions = new Array();
		
		// create our loading image
		this.zb_loading = new Element('img', { 
			'id'    : 'zb_loading', 
			'src'   : this.options.zb_loader,
			'styles': { 
				'position': 'absolute',
				'display' : 'none',
				'left'    : 0,
				'top'     : 0
			}
		}).inject(document.body, 'bottom');

		// scan page for our class.
		this.thumbs = $$(this.options.zb_class);
		
		var self = this;
		
		// attach each image.
		this.thumbs.each(function(zb, index) {
			self.attach(zb, index);
		});
		
		// add event listener if the user resizes their window to scale max size of images.
		window.addEvent('resize', self.setWindowSize.bindWithEvent(this));
		
	},
	
	
	// attach out image and add event listeners.
	attach: function(zb, index) {
		var self     = this;
		// is we manually attach a new element this is needed.
		if(index == undefined) {
			index = (self.length + 1);
		}
		// set our basic width/heights.
		var zb_fx;
		var zb_src   = zb.get('href');
		var zb_org   = zb.getElements('img')[0];
		self.positions[index] = {};
		self.positions[index].zb_left = zb_org.getPosition().x;
		self.positions[index].zb_top  = zb_org.getPosition().y;
		// add out click event.
		zb.addEvent('click', function(clk) {
			new Event(clk).stop();
			// no point opening it, if its already open !
			if(!document.id(self.options.zb_element) || !document.id(self.options.zb_element).get('src').match(zb.get('href'))) {
				// add out loading gif to the image about to be opened.
				self.zb_loading.setStyles({
					'display' : '',
					'top'     : self.positions[index].zb_top,
					'left'    : self.positions[index].zb_left
				});
				// if we have one open, let it be gone
				if(document.id(self.options.zb_element)) {
					self.close(self.currentIndex);
				}
				// set current index.
				self.currentIndex = index;
				// create and place on top of the thumbnail. but keep it hidden.
				self.images[index] = new Element('img', { 
					'id'    : self.options.zb_element, 
					'src'   : zb_src,
					'styles': { 
						'position': 'absolute',
						'opacity' : 0,
						'left'    : self.positions[index].zb_left,
						'top'     : self.positions[index].zb_top
					}
				})
				.addClass('shadow') // we don't need this. but its basic styling for large image.
				.inject(document.body, 'bottom') // inject at teh bottom of our page.
				.addEvent('click', function(clk) {
					// bind out close even on clicking the new large image
					new Event(clk).stop();
					self.close(index);
				})
				// bind a load event so once the large image has loaded, we open it.
				.addEvent('load', function() {
					// get our large image size
					var zb_width  = self.images[index].getWidth();
					var zb_height = self.images[index].getHeight();
					// see if we need to scale it, so the image fits on screen.
					if(self.options.scale_image) {
						if(self.options.win_width < zb_width) {
							zb_width  = (self.options.win_width - 50);
							zb_height = (zb_width / zb_height) * zb_width;
						} 
						if(self.options.win_height < zb_height) {
							zb_height = Math.floor(self.options.win_height - 50);
							zb_width  = Math.floor((zb_height / zb_width) * zb_height);
						}
					}
					// set the imahe the size of the thumbnail
					self.images[index].setStyles({
						'width'   : zb_org.getWidth(),
						'height'  : zb_org.getHeight(),
						'cursor'  : 'pointer'
					});
					// hide teh loading gif/indicator 
					self.zb_loading.setStyle('display', 'none');
					// animate it BIG ! and center it on the screen
					var zb_fx = new Fx.Morph(self.images[index]).start({
						'top'     : ((self.options.win_height / 2) - (zb_height / 2)) + window.getScroll().y,
						'left'    : ((self.options.win_width / 2) - (zb_width / 2)),
						'width'   : zb_width,
						'height'  : zb_height,
						'opacity' : 1
					});
				});
			} else {
				// we have used it before, lets load it up.
				self.images[index].fireEvent('load');
			}
			// bind the 'escape' key to close the current image.
			window.addEvent('keyup', function(key) {
				if(key.code == 27) {
					self.close(index);
				} 
			});
		});
	},
	
	close: function(index) {
		var self = this;
		var zb_fx = new Fx.Morph(self.images[index], { 
			onComplete: function() {
				document.id(self.options.zb_element)
					.fade(0)
					.dispose();
			} 
		}).start({
			'top'     : self.positions[index].zb_top,
			'left'    : self.positions[index].zb_left,
			'width'   : 100,
			'height'  : 100,
			'opacity' : 0
		});
		window.removeEvents('keyup');
	},
	
	setWindowSize: function() {
		
		this.options.win_width = window.getWidth();
		this.options.win_height = window.getHeight();
		
	}
	
});

Download the Full Script:
[download id="11"]

Using Mootools Request.HTML response Javascript using $exec

Javascript frameworks are great, no matter which one you use their all built to do more, quickly.

I use Mootools for most of my JS needs, and something is I often use is the AJAX request functionality.

Today I needed to send not only HTML back, but Javascript.

Here are the steps I needed to follow to not only return my Javascript, but to attach it to my response with the Mootools function ‘$exec’

My HTML

Update

My Mootoold Javascript

	

Our Request Handler PHP script





< ?php

	/* QUERY OUR RECORDS FROM OUR GET DATA */

	$response = mysql_get_data_function($_GET);

	echo($response);

?>

Final Response

After running this ‘update’ script, we will have displayed information based on our GET data in the div ‘container’, removed our update link, shown a success message, and styled everything with out response javascript, all thanks to our nifty Mootools $exec function.

Non-Ascii charactors in my AJAX responses !?

A while ago, I co-wrote a large site with Ryan while I was working at Zipline Interactive, this site uses Mootools 0.98 as we found to be getting a lot of �������� all through the JAX requested response code.

For the life of US, we couldn’t figure out why? it’s not in the output if we called the data via a normal http request, so I looked for a fix.

  1. Upgrade the Mootools to version 1.2.2
  2. Add an enc type to the AJAX functions
    	new Request.HTML({
    		method: 'get',
    		url: '/examples/ajax.php',
    		data: { 'example': 'ajax-ascii' },
    		encoding: 'iso-8859-1',
    		onRequest: function() {
    			$('calendarMainEvent').empty().removeClass('calendarClosed');
    			$('calendarMainEvent').set('html', 'Loading');
    		},
    		onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
    			$('calendarMainEvent').empty().set('html', responseHTML);
    			$('calendarMainEvent').setProperty('class','calendarOpen');
    		},
    		onFailure: function() {
    			$('calendarMainEvent').empty().removeClass('calendarClosed');
    		}
    	}).send();
    
  3. Specifying the charset in the PHP that is outputting the AJAX response!

    < ?php
    
    if($_GET['ajax_request']) {
    
    header('Content-Type: text/html; charset=iso-8859-1');
    echo('

    Success'); /* More output code */ }

Matching the Character set

It didn’t occur to me right away that I need to specify the charset more than just in the <head> section of the page, but that was all it took.

Of course you want to match your PHP header, Javascript encoding and xHTML charsets all to the same with it is iso-xxx or utf-xx

Controlling Input with Mootools Javascript

On a project that I was recently working on, I had a series of text input boxes that I wanted to be numeric only fields. I have my PHP form validation to check that the data is numeric before entering any information in to the database, and I always use mysql_real_escape_string() on the data I am saving. But to save loat time and page refreshed, I decided to add some extra validation with the Mootools javascript library which I am using trough out the site already.

View Example

Update to Numbers Array

I have updated the Numbers array to include the number pad on full size keyboards.

Allowing Numbers:

Because I have a bunch of inputs that I need validated, I decided that I would assign each input with a matching class, then Scan the page for that class with my Javascript, then only allow specific key codes to be entered.

Your Age...

Inside of my DOM Ready state, I run this simple code.

window.addEvent('domready', function() {
	var numbers = [8, 48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];
	$$('.numeric').each(function(item) {
		item.addEvent('keydown', function(key) {
			for (i = 0; i < numbers.length; i++) {
				if(numbers[i] == key.code) {
					return true;
				}
			}
			return false;
		});
	});
});

If you can see the line I have specified only the Key Codes that are allows, I have allowed for numeric numbers and the Delete Key.

	var numbers = [8, 48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];

Other Uses:

You could disallow any key entry, This isnt a great idea, but could be used when maybe using an overlay, or special effect.

window.addEvent('domready', function() {
	window.addEvent('keydown', function() {  return false; });
});

Dissallowing Keys:

You could simply reverse this function, to block a small amount of keys rather than just allowing some, it would be as simple as changing the locations of your return true/false statements.

This example would allow anything except numbers.

window.addEvent('domready', function() {
	var numbers = [48,49, 50, 51,52,53,54,55,56,96,97,98,99,100,101,102,103,104,105];
	$$('.numeric').each(function(item) {
		item.addEvent('keydown', function(key) {
			for (i = 0; i < numbers.length; i++) {
				if(numbers[i] == key.code) {
					return false;
				}
			}
			return true;
		});
	});
});

BounceBox Update, Version 1.1

I was using an implementation of my BounceBox mootools javascript class on a site I am working on at the moment, and made a couple of additions to the Class that I hope other will enjoy.

The new version1.1 demo can be viewed at http://bouncebox.lendrum.co.nz/ and the change log with a new version 1.1 demo link at the bottom of that page to show full screen positioning that is now supported.

The Demo page has full links to download this free Mootools Javascript effects class.

Alternating row styles with Javascript

I am writing a list that outputs a large amount of data in a vertical structure, with many rows the list gets hard to tell which entry is which.

Now, normally I would do this via PHP, something like

	< ?php $messages = SQL('QUERY TO GET MY MESSAGES'); ?>
	< ?php $style    = "on"; ?>
	< ?php if($messages): ?>
	

Messages

< ?php foreach($messages as $message): ?>
>

< ?=date('d/m/Y', strtotime($message->last_modified))?> < ?=$message->firstname?> < ?=$message->lastname?>

< ?=$message->message?>

< ?=$message->status?>

< ?php if($style=='on') { $style = 'off' } else { $style = 'on'} ?> < ?php endforeach; ?> < ?php endif; ?>

But I decided today to write it in Javascript. Mootools 1.2 in fact, as the site I am working on had a lot of cool JS effects.

The HTML

	< ?php $messages = SQL('QUERY TO GET MY MESSAGES'); ?>
	< ?php if($messages): ?>
	

Messages

< ?php foreach($messages as $message): ?>

< ?=date('d/m/Y', strtotime($message->last_modified))?> < ?=$message->firstname?> < ?=$message->lastname?>

< ?=$message->message?>

< ?=$message->status?>

< ?php endforeach; ?> < ?php endif; ?>

The Javascript

	$$('.message').each(function(message, row) { // find all elements the have a class called 'message' and loop trough them.
		if(row%2) message.setStyle('background', '#eceff1'); // assign my style to it
	});

You can assign more than one style, by using Mootools setStyles({ }); function. or add events. Eg;

	$$('.message').each(function(message, row) {
		if(row%2) message.setStyle('background', '#eceff1');
		var background = message.getStyle('background');
		message.setStyle('padding', '5px');
		message.addEvents({
			'mouseenter': function() { message.setStyle('background', '#d2d2d2'); },
			'mouseleave': function() { message.setStyle('background', background); }
		});
	});

This will assign a different style and an event back to each element.

Demo:

Hover over any of the below messages :)

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

23/03/2009
Sheldon Lendrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

0

‘BounceBox’ Mootools Effects Class

I sat down to further my Javascript skills a couple of weeks ago and re-wrote a small peice of code that I used on DreamCatcher, A School Careers Application to create ‘Slide Down’ boxes for the Contact Form, Login Form and an Introduction Movie.

I rewrote it using less code and working out heights and sizes more dynamically, but yesterday I decided that I wanted to write a Mootools Javascript Class, something I have never attempted. So here is the first version 1.0. A simple Javascript class for Mootools 1.2+ to display a sliding box with a nice tranisiton and with/out an overlay layer.

This Class requires no CSS styles other that cosmetic formatting, and can be called via DOM READY or an Event. If the BounceBox is open, then your ESC key will close the BounceBox.

I have tested it, and works on;

Safari ( Mac & Win )
FireFox 3 ( Mac & Win )
IE 6 & 7

This is a free Release and I welcome any and all bugs and suggestions.

Now Version 1.2

View the Example at http://bouncebox.lendrum.co.nz or Download;

Version 1.2 [download id="10"]
Version 1.1 [download#8]
Version 1.0 [download#7]

BouceBox Preview

BouceBox Preview

Update to Jess Thompson Photography.com

A couple of weeks ago I posted about setting up a web gallery for my friend Jessye Thompson.

Well after me being really busy, slack and all of the above, It is now up and running smoothly and you can visit the site at www.jessthompsonphotography.com. If you live in the North West USA, and are looking for a good photographer for any event, Contact Jess.

The site uses valid xhtml and CSS plus some pretty Mootools effects including Slimbox lightbox by Christophe Beyls.

I have tried using lots of bright colours on a dark background to give it a clean and modern look with a bit of fun and colour to go with the great photos.

Let me or more importantly Jess know any feedback.