Safari Firefox Chrome You are using Internet Explorer. Have you considered upgrading?
Mar 11th, 2010 by Barker Design
Book Review: MooTools 1.2 Beginner’s Guide

MooTools Book

In the interest in full disclosure, I was sent this book by Packt Publishing in hopes that I would review it. I’m reviewing this book, however, in the interest of my audience.

Unless you live under a rock or simply check my site for Christina Ricci pics every morning, you know I’m a bit of a MooTools fanboy. I spend hours every day writing MooTools tutorials, getting in touch with the MooTools community and development team members, and oh yeah…coding a bit too. When it was brought to my attention that Jacob Gube and Garrick Cheung had written a MooTools book for beginners, I was really excited to check it out. The following are my thoughts on their book.

The Authors

Jacob Gube, Garrick Cheung

The Tagline

Learn how to create dynamic, interactive, and responsive cross-browser web applications using this popular JavaScript framework.

Shooting From the Hip

Instead of giving you this super long review that you wont read, I’ve decided to put my thoughts into bullet format. How clever!

  • What I really love about this book is that it’s not a bunch of “theory” information — it’s no-nonsense, code-based learning. I LOVE these style of books.
  • The book is ~ 150 pages, which is about right for a beginner’s guide. Making it too long would be a huge mistake.
  • The price point is $40. Reasonable.
  • The book covers a large array of sample projects and code examples — you aren’t looking at the same code snippets everywhere. Awesome.
  • One gripe is that I don’t recall the book ever discussing the difference between MooTools and similar libraries like jQuery, Dojo, etc. MooTools’ object-oriented architecture and the idea of modifying native object prototypes is core to the framework and differentiates MooTools from other libraries. That really should be included in a “version 2″ book.
  • I was not included as a MooTools resource — clearly an oversight. Hahaha.
  • The book *does* cover creating a unique build of MooTools Core and -More. This is very important as beginners should know that MooTools is built to be incredibly modular and Moo programmers should code with that same idea in mind.
  • The book flows very well and the progression of difficulty is perfect. Beginners will really appreciate the pace of the book.
  • While Jacob isn’t a member of the team, he co-authored with contributor Garrick Cheung and asked Christoph Pojer, a MooTools Core Developer, to be technical reviewer. Involving people very close to the team was a great idea; it helps the book’s credibility and allows for all options to be considered. * I don’t mean to say this to discredit Jacob — he’s done a great job with this book and you certainly don’t need to be a team member/contributor to be a MooTools expert.
  • I know it’s Packt’s style, but the “Impact”-style heading fonts are ugly.
  • The book doesn’t try to explain or gloss over basic javascript. Thank you, thank you, thank you!

The Verdict

I was very impressed with this book and I believe it’s the perfect book for any developer looking to enter the MooTools pastures. My only major desire is that the book cover MooTools’ native object prototype modification; beside that oversight, I’d recommend this book to both rookie and novice MooTools developers. MooTools 1.2 Beginner’s Guide should be required reading for MooTools developers looking to master the basic of MooTools.

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Book Review: MooTools 1.2 Beginner’s Guide

Related posts:

  1. Book Review: Enterprise Ajax — Strategies For Building High Performance Web Applications
  2. Book Review: PHP5 CMS Framework Development
  3. Book Review: Wicked Cool PHP
  4. Book Review: Ajax Security
  5. Free SitePoint Ruby on Rails Book!

 
Mar 11th, 2010 by Barker Design
Create Twitter-Style Dropdowns Using MooTools

Twitter Dropdown

Twitter does some great stuff with javascript. What I really appreciate about what they do is that there aren’t any epic JS functionalities — they’re all simple touches. One of those simple touches is the “Login” dropdown on their homepage. I’ve taken some time to duplicate that functionality with MooTools.

View Demo

The HTML

<div id="menu1"><div class="relative">
	<a href="/demos" title="Popular MooTools Tutorials" id="dd1" class="dropdown" style="width:170px;text-decoration:none;"><span>Menu 1</span></a>
	<div id="dropdown1" class="dropdown-menu">
		<a href="/about-david-walsh" title="Learn a bit about me.">About Me</a>
		<a href="/page/1" title="The David Walsh Blog">Blog</a>
		<a href="/chat" title="#davidwalshblog IRC Chat">Chat</a>
		<a href="/contact" title="Contact David Walsh">Contact Me</a>
		<a href="/demos" title="CSS, PHP, jQuery, MooTools Demos">Demos &amp; Downloads</a>
		<a href="/js" title="ScrollSpy, Lazyload, Overlay, Context Menu">MooTools Plugins</a>
		<a href="/network" title="David Walsh Blog, Script &amp; Style, Band Website Template, Wynq">Network</a>
		<a href="/web-development-tools" title="JS, CSS Compression">Web Dev Tools</a>
	</div>
</div></div>

<div id="menu2"><div class="relative">
	<a href="/demos" title="Popular MooTools Tutorials" id="dd2" class="dropdown" rel="dropdown2" style="width:170px;text-decoration:none;"><span>Menu 2</span></a>
	<div id="dropdown2" class="dropdown-menu">
		<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
	</div>
</div></div>

A series of DIVS wrapping a link (the dropdown “trigger”) and a DIV containing the menu items.

The CSS

/* dropdowns: general */
a.dropdown { background: #88bbd4; padding: 4px 6px 6px; text-decoration: none; font-weight: bold; color: #fff; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; }
a.dropdown:hover { background: #59b; }
a.dropdown { position: relative; margin-left: 3px; }
a.dropdown span { background-image: url(toggle_down_light.png); background-repeat: no-repeat; background-position: 100% 50%; padding: 4px 16px 6px 0; }
a.dropdown.dropdown-active { color:#59b; background-color:#ddeef6; }
a.dropdown.dropdown-active span { background:url(toggle_up_dark.png) 100% 50% no-repeat; }
.dropdown-menu	{ background:#ddeef6; padding:7px 12px; position:absolute; top:16px; right:0; display:none; z-index:5000; -moz-border-radius-topleft: 5px; -moz-border-radius-bottomleft: 5px; -moz-border-radius-bottomright: 5px; -webkit-border-top-left-radius: 5px; -webkit-border-bottom-left-radius: 5px; -webkit-border-bottom-right-radius: 5px; }
	.dropdown-menu p { font-size:11px; }
.dropdown-menu a:link, .dropdown-menu a:visited	{ font-weight:bold; color:#59b; text-decoration:none; line-height:1.7em; }
.dropdown-menu a:active, .dropdown-menu a:hover { color:#555; }

/* dropdowns: specific */
#menu1			{ float:left; margin-right:20px; }
	#dropdown1	{ width:150px; }
	#dropdown1 a	{ display:block; }
#menu2			{ float:left; }
	#dropdown2	{ width:150px; font-size:11px; }
.relative		{ position:relative; }

There’s a lot of CSS involved but most of it is simple visual styling as opposed to styling for javascript’s sake. Do, however, note where relative and absolute positioning is used. The outermost DIV may be positioned absolutely if you’d like. Also note that I’m not doing anything to accommodate for rounded corners in IE — I recommend DD_Roundies for that.

The MooTools Javascript

window.addEvent('domready',function() {
	(function($) {
		/* for keeping track of what's "open" */
		var activeClass = 'dropdown-active', showingDropdown, showingMenu, showingParent;
		/* hides the current menu */
		var hideMenu = function() {
			if(showingDropdown) {
				showingDropdown.removeClass(activeClass);
				showingMenu.setStyle('display','none');
			}
		};
		/* recurse through dropdown menus */
		$$('.dropdown').each(function(dropdown) {
			/* track elements: menu, parent */
			var menu = dropdown.getNext('div.dropdown-menu'), parent = dropdown.getParent('div');
			/* function that shows THIS menu */
			var showMenu = function() {
				hideMenu();
				showingDropdown = dropdown.addClass('dropdown-active');
				showingMenu = menu.setStyle('display','block');
				showingParent = parent;
			};
			/* function to show menu when clicked */
			dropdown.addEvent('click',function(e) {
				if(e) e.stop();
				showMenu();
			});
			/* function to show menu when someone tabs to the box */
			dropdown.addEvent('focus',function() {
				showMenu();
			});
		});
		/* hide when clicked outside */
		$(document.body).addEvent('click',function(e) {
			if(showingParent && !e.target || !$(e.target).getParents().contains(showingParent)) {
				hideMenu();
			}
		});
	})(document.id);
});

I’ve commented to the code to illustrate what each block does. In a nutshell:

  • I create placeholder variables which will keep track of the current menu, dropdown, and parent for the opened menu. This functionality is only included because I don’t want more than one menu to be open at a time.
  • I create a function that hides the current menu — this can be used from anywhere within the closure.
  • I cycle through each dropdown and add events to relevant elements to show and hide menus.
  • I add an event to the body to close the current menu if the user clicks outside of the menu.

That’s it!

View Demo

Look forward to a MooTools Class version soon. Also look forward to jQuery and Dojo versions!

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Create Twitter-Style Dropdowns Using MooTools

Related posts:

  1. NetTuts Exclusive: Twitter Emulation Using MooTools 1.2 and PHP
  2. David Walsh on NetTuts: Create a Twitter-Like “Load More” Widget
  3. Follow Script & Style on Twitter!
  4. Select Dropdowns, MooTools, and CSS Print
  5. Create Snook-Style Navigation Using MooTools

 
Mar 10th, 2010 by Barker Design
Introducing MooTools NextPrev

MooTools NextPrev

One thing I love doing is duplicating OS functionalities. One of the things your OS allows you to do easily is move from one item to another. Most of the time you’re simply trying to get to the next or the previous item. MooTools NextPrev is a compact javascript class that allows you to move about a collection of items quickly using human terms.

View Demo

The MooTools Class

var NextPrev = new Class({
	Implements: [Options,Events],
	options: {
		baseEvent: 'keyup',
		eventContainer: document,
		eventCheckNext: function(e){
			return true;
		},
		eventCheckPrevious: function(e){
			return true;
		},
		onLoad: $empty,
		onNext: $empty,
		onPrevious: $empty,
		startIndex: 0
	},
	initialize: function(collection,options) {
		this.setOptions(options);
		this.collection = $$(collection);
		if(this.options.container == document) this.options.container = document.body;
		this.index = this.options.startIndex;
		if(this.options.baseEvent) {
			$(this.options.eventContainer).addEvent(this.options.baseEvent,function(e) {
				if(this.options.eventCheckNext(e)) {
					this.move.bind(this)('next');
				}
				else if(this.options.eventCheckPrevious(e)) {
					this.move.bind(this)('previous');
				}
			}.bind(this));
		}
		this.fireEvent('load',[this.collection[this.index]]);
	},
	move: function(norp) {
		var previous = this.index;
		switch($type(norp)) {
			case 'string':
				var ev = 'next';
				if(norp == 'next') {
					var plus = this.index + 1;
					this.index = this.collection[plus] ? plus : 0;
				}
				else {
					var minus = this.index - 1;
					this.index = this.collection[minus] ? minus : this.collection.length-1;
					ev = 'previous';
				}
				this.fireEvent(ev,[this.collection[this.index],this.collection[previous]]);
				break;
			case 'element':
				this.index = this.collection.indexOf(norp) || 0;
				break;
			default:
				this.index = norp;
				break;
		}
		this.fireEvent('change',[this.collection[this.index],this.collection[previous]]);
		return this;
	}
});

The following are arguments, options, and events for NextPrev:

Arguments

  • collection: The collection of elements..
  • options: The instance options.

Options

  • baseEvent: (defaults to ‘keyup’) The event to listen to.
  • eventContainer: (defaults to document) The event listener container.
  • eventCheckNext: (defaults to function) The function that decides if the conditions to trigger a “next” have been met.
  • eventCheckPrevious: (defaults to function) The function that decides if the conditions to trigger a “previous” have been met.
  • startIndex: (defaults to 0) The starting index for the collection.

Events

  • change: Fired when the index changes.
  • load: Fired every time the class is initialized.
  • next: Fired when the next directive is triggered.
  • previous: Fired when the previous directive is triggered.

Public Methods

  • move: May be passed the Strings “next” or “prev”, or a DOM node.

Sample Usage

var np2 = new NextPrev($$('#images img'),{
	eventCheckNext: function(e) {
		if(e) e.stop(e);
		return e.key == 'right';
	},
	eventCheckPrevious: function(e) {
		if(e) e.stop(e);
		return e.key == 'left';
	},
	onNext: function(cur,prev) {
		prev.removeClass('featured');
		cur.addClass('featured');
	},
	onPrevious: function(cur,prev) {
		prev.removeClass('featured');
		cur.addClass('featured');
	},
	onLoad: function(cur) {
		cur.addClass('featured');
	}
});

The code above hijacks the “left” and “right” keys, moving forward and backward in the collection depending on which key was pressed.

View Demo

NextPrev is extremely simple but also quite flexible. You decide the events, keys, actions, etc — the plugin simple allows for simple control of position in the list. Have ideas for this class? Know what you’d use it for? Let me know!

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Introducing MooTools NextPrev

Related posts:

  1. Create a Simple News Scroller Using MooTools, Part I: The Basics
  2. Introducing MooTools ScrollSidebar
  3. Introducing MooTools LinkAlert
  4. Introducing MooTools Dotter
  5. Create a Simple Slideshow Using MooTools, Part II: Controls and Events

 
Mar 9th, 2010 by Barker Design
Create a Simple News Scroller Using Dojo

My journey into Dojo javascript has been exciting and I’m continuing to learn more as I port MooTools scripts to Dojo. My latest experiment is porting a simple new scroller from MooTools to Dojo. The code is very similar!

View Demo

The HTML

  • News Item 1Pellentesque habitant morbi...Read More
  • News Item 2Pellentesque habitant morbi...Read More

The news items are placed into list items. The UL will be the element that’s animated.

The CSS

#news-feed	 { height:200px; width:300px; overflow:hidden; position:relative; border:1px solid #ccc; background:#eee; }
#news-feed ul	{ position:absolute; top:0; left:0; list-style-type:none; padding:0; margin:0; }
#news-feed ul li { min-height:180px; font-size:12px; margin:0; padding:10px; overflow:hidden; }

The absolute positioning is essential to proper animation. Unlike my MooTools example, this example no longer requires a fixed height for each news item. I did add a minimum height so only one item shows up within the scroller window at a time.

The Dojo Javascript

dojo.require('dojo.NodeList-fx');
dojo.addOnLoad(function() {
	/* settings */
	var list = dojo.query('#news-feed ul'),
		items = list.query("li"),
		showDuration = 3000,
		scrollDuration = 500,
		scrollTopDuration = 200,
		index = 0,
		interval;

	/* movement */
	var start = function() { interval = setInterval(move,showDuration); };
	var stop = function() { if(interval) clearInterval(interval); };
	var reset = function() {
	    list.anim({ top: 0}, scrollTopDuration, null, start);
	};
	/* action! */
	var move = function() {
	    list.anim({ top: (0 - (dojo.coords(items[++index]).t)) }, scrollDuration, null, function(){
			if(index == items.length - 1) {
				index = 0-1;
				stop();
				setTimeout(reset,showDuration);
			}
	    });
	};

	/* stop and start during mouseenter, mouseleave  */
	list.onmouseenter(stop).onmouseleave(start);

	/* go! */
	start();
});

This is where I have the epic description…but the above code (at least for MooTools users) should look familiar. The logic is exactly the same but the code uses dojo.* methods instead of MooTools’ Fx, $$, $, and Element.Dimensions methods.

The MooTools Javascript

window.addEvent('domready',function() {
	/* settings */
	var list = $('news-feed').getFirst('ul');
	var items = list.getElements('li');
	var showDuration = 3000;
	var scrollDuration = 500;
	var index = 0;
	var height = items[0].getSize().y;
	/* action func */
	var move = function() {
		list.set('tween',{
			duration: scrollDuration,
			onComplete: function() {
				if(index == items.length - 1) {
					index = 0 - 1;
					list.scrollTo(0,0);
				}
			}
		}).tween('top',0 - (++index * height));
	};
	/* go! */
	window.addEvent('load',function() {
		move.periodical(showDuration);
	});
});

The above code was taken from my original post. Take a moment to compare the Dojo and MooTools code.

View Demo

What do you think? Three Dojo posts in — what are your thoughts about Dojo to this point?

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Create a Simple News Scroller Using Dojo

Related posts:

  1. Create a Simple News Scroller Using MooTools, Part I: The Basics
  2. Link Nudging Using Dojo
  3. Remove Broken Images Using Dojo
  4. QuickBoxes for Dojo
  5. Using MooTools 1.2 For Drag, Drop, Sort, Save

 
Mar 8th, 2010 by Barker Design
“MooTools as a General Purpose Application Framework” by Christoph Pojer

I wanted to bring attention to an outstanding presentation given by MooTools Core Developer Christoph Pojer.  Given at FOSDEM 2010, Christoph provides an overview of what MooTools is, who should use it, how it should be used.  Examples are given throughout the presentation. 

I highly recommend MooTools users of all experience levels watch this video, as well as jQuery or Dojo users looking to simply understand what this framework is about.

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

“MooTools as a General Purpose Application Framework” by Christoph Pojer

Related posts:

  1. Following MooTools on Twitter
  2. When Javascript Frameworks Collide
  3. What Would You Like From Your Framework?
  4. 5 Ways to Contribute to Your Favorite Javascript Framework
  5. Book Review: PHP5 CMS Framework Development

 
Mar 2nd, 2010 by Barker Design
Remove Broken Images Using Dojo

In an effort to get better with the Dojo Toolkit, I’ve decided to port yet another one of my previous posts: Remove Broken Images Using MooTools or jQuery. Broken images are an eyesore to any website so there’s no point to keeping them in the page. Here’s how you can remove them on the client side.

The Dojo Javascript

dojo.ready(function() {
	dojo.query('img').forEach(function(img){
		dojo.connect(img,'onerror',function() {
			dojo.destroy(img);
		});
	});
});

Just as simple as jQuery and MooTools — just a different syntax!

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Remove Broken Images Using Dojo

Related posts:

  1. Remove Broken Images Using MooTools or jQuery
  2. Link Nudging Using Dojo
  3. QuickBoxes for Dojo
  4. Send Email Notifications for Broken Images Using MooTools Ajax
  5. Send Email Notifications for Broken Images Using jQuery Ajax

 
Mar 1st, 2010 by Barker Design
Link Nudging Using Dojo

Dojo Toolkit

In the past we’ve tinkered with link nudging with MooTools and link nudging with jQuery. In an effort to familiarize myself with other javascript frameworks, we’re going to try to duplicate that effect with another awesome framework: Dojo.

View Demo

The Javascript: Attempt 1

dojo.addOnLoad(function() {
	var links = dojo.query('a.nudge');
	//foreach...
	dojo.forEach(links,function(link) {
		var left = dojo.style(link,'paddingLeft');
		dojo.connect(link,'onmouseenter',function() {
			dojo.animateProperty({
				node:link,
				properties: {
					paddingLeft: 20
				}
			}).play();
		});
		dojo.connect(link,'onmouseleave',function() {
			dojo.animateProperty({
				node:link,
				properties: {
					paddingLeft: left
				}
			}).play();
		});
	});
});

Once the DOM is ready, we use the dojo.query method to find all of the links to nudge. For every link we find, we record its original left padding and add mouseenter and mouseleave events to each link to animate its left padding.

The Javascript: Better Solution

dojo.ready(function() {
	dojo.query('a.nudge').forEach(function(link){
		var left = dojo.style(link,'paddingLeft');
		dojo.connect(link,'onmouseenter',function() {
		    dojo.anim(link, { paddingLeft:20 });
		});
		dojo.connect(link,'onmouseleave',function() {
		    dojo.anim(link, { paddingLeft:left });
		});
	});
});

Dojo lead Pete Higgins showed me a more condensed version of his script.

View Demo

Simple, no? The best way to learn to use any javascript framework is to duplicate a given set of code you are familiar with, much like we did here. What do you think about this Dojo example? Look close to jQuery and MooTools?

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Link Nudging Using Dojo

Related posts:

  1. jQuery Link Nudging
  2. QuickBoxes for Dojo
  3. MooTools Link Nudging
  4. jQuery Link Nudge Plugin
  5. jQuery Random Link Color Animations

 
Feb 26th, 2010 by Barker Design
jQuery Podcast & Essential jQuery and MooTools Snippets

jQuery

Many of you probably already know this but I like to consider myself a bit of a javascript chameleon. If you know that then you probably know I’m a MooTools fanatic that periodically dabbles with jQuery. I’m happy to announce that I was able to join Elijah Manor and Ralph Whitbeck on the jQuery podcast this past week to talk jQuery, MooTools, and web development in general. Head on over to the jQuery blog for more information or iTunes to grab the podcast.

As an extension of my podcast appearance, I wanted to share a few code snippets to make your introduction to MooTools or jQuery easier.

Featured jQuery & MooTools Snippets

Using jQuery and MooTools Together

Did you know that you can use jQuery and MooTools within the same page? It’s easy to!

<script type="text/javascript" src="moo1.2.4.js"></script>
<script type="text/javascript" src="jquery-1.4.js"></script>
<script type="text/javascript">
window.addEvent('domready',function() { //moo stuff
	$('p').css('border','1px solid #fc0'); //jquery
});
</script>

Using Sizzle Within MooTools

Prefer to use jQuery’s selector engine within MooTools? No problem — here’s how:

//just as reader "Ryan" mentioned....
Window.$$ = function(selector){
	return new Elements(new Sizzle(selector));
}

jQuery and MooTools Link Nudging

Link nudging is a classy, subtle effect that makes your websites more dynamic.

/* jquery */
$.fn.nudge = function(params) {
	//set default parameters
	params = $.extend({
		amount: 20,
		duration: 300,
		property: 'padding',
		direction: 'left',
		toCallback: function() {},
		fromCallback: function() {}
	}, params);
	//For every element meant to nudge...
	this.each(function() {
		//variables
		var $t = $(this);
		var $p = params;
		var dir = $p.direction;
		var prop = $p.property + dir.substring(0,1).toUpperCase() + dir.substring(1,dir.length);
		var initialValue = $t.css(prop);
		/* fx */
		var go = {}; go[prop] = parseInt($p.amount) + parseInt(initialValue);
		var bk = {}; bk[prop] = initialValue;

		//Proceed to nudge on hover
		$t.hover(function() {
					$t.stop().animate(go, $p.duration, '', $p.toCallback);
				}, function() {
					$t.stop().animate(bk, $p.duration, '', $p.fromCallback);
				});
	});
	return this;
};

/* jquery usages */
$(document).ready(function() {
	/* usage 1 */
	$('#nudgeUs li a').nudge();
	/* usage 2 */
	$('#nudgeUs2 li a').nudge({
		property: 'margin',
		direction: 'left',
		amount: 30,
		duration: 400,
		toCallback: function() { $(this).css('color','#f00'); },
		fromCallback: function() { $(this).css('color','#000'); }
	});
});

/* mootols link nudge */
window.addEvent('domready',function() {
	$$('#nudges a').addEvents({
		'mouseenter': function() { this.tween('padding-left',20); },
		'mouseleave': function() { this.tween('padding-left',0); }
	});
});
View jQuery Demo View jQuery Demo

jQuery and MooTools Search Bookmarklets

These bookmarklets will allow you to highlight text on a page and search the jQuery or MooTools websites to learn more about the phrase.

jQuery BookmarkletMooTools Bookmarklet

 

jQuery Events within MooTools

The following MooTools snippet allows you to use jQuery-style syntax for event listening.

//hash the element.natives so we can do stuff with it
var hash = new Hash(Element.NativeEvents);
//remove items that need to be replaced, add their replacements
hash.erase('mouseover').erase('mouseout').erase('DOMMouseScroll');
hash.include('mouseenter',1).include('mouseleave',1);
//initialize this
var eventHash = new Hash({});
//for every event type, add to our hash
hash.getKeys().each(function(event){
	eventHash[event] = function(fn) {
		this.addEvent(event,fn);
		return this;
	}
});
//make it happen
Element.implement(eventHash);

 

JavaScript FTW!

Here are a few other MooTools and jQuery tutorials you may like:

Isn’t the javascript community great? MooTools FTW!

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

jQuery Podcast & Essential jQuery and MooTools Snippets

Related posts:

  1. jQuery Link Nudge Plugin
  2. Implementing jQuery-Like Event Syntax in MooTools
  3. Using jQuery and MooTools Together
  4. Count MooTools Events Per Element in MooTools 1.2
  5. Implement MooTools’ Elements.addEvent in jQuery

 
Feb 25th, 2010 by Barker Design
Fixing Python’s “Python Eggs” Error

Let me first state this for the record: I am not a server guy. The closest I’ve ever gotten to compiling my own versions of code is “sudo port install …” So when I decided to teach myself Python (creating simply database interaction, record listings, etc) and kept getting “500 Internal Server Error” messages, I thought I was doomed. I opened up the Apache error log and saw this:

[error] [client ::1] Traceback (most recent call last):
[error] [client ::1]   File "/Users/davidwalsh83/Projects/server/something.py", line 6, in <module>
[error] [client ::1]     import MySQLdb, cgi, cgitb, httplib, urllib2
[error] [client ::1]   File "build/bdist.macosx-10.6-universal/egg/MySQLdb/__init__.py", line 19, in <module>
[error] [client ::1]   File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 7, in <module>
[error] [client ::1]   File "build/bdist.macosx-10.6-universal/egg/_mysql.py", line 4, in __bootstrap__
[error] [client ::1]   File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py", line 835, in resource_filename
[error] [client ::1]     self, resource_name
[error] [client ::1]   File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py", line 1304, in get_resource_filename
[error] [client ::1]     self._extract_resource(manager, self._eager_to_zip(name))
[error] [client ::1]   File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py", line 1326, in _extract_resource
[error] [client ::1]     self.egg_name, self._parts(zip_path)
[error] [client ::1]   File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py", line 915, in get_cache_path
[error] [client ::1]     self.extraction_error()
[error] [client ::1]   File "/System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources.py", line 881, in extraction_error
[error] [client ::1]     raise err
[error] [client ::1] pkg_resources.ExtractionError: Can't extract file(s) to egg cache
[error] [client ::1]
[error] [client ::1] The following error occurred while trying to extract file(s) to the Python egg
[error] [client ::1] cache:
[error] [client ::1]
[error] [client ::1]   [Errno 20] Not a directory: '/Library/WebServer/.python-eggs/MySQL_python-1.2.3c1-py2.6-macosx-10.6-universal.egg-tmp'
[error] [client ::1]
[error] [client ::1] The Python egg cache directory is currently set to:
[error] [client ::1]
[error] [client ::1]   /Library/WebServer/.python-eggs
[error] [client ::1]
[error] [client ::1] Perhaps your account does not have write access to this directory?  You can
[error] [client ::1] change the cache directory by setting the PYTHON_EGG_CACHE environment
[error] [client ::1] variable to point to an accessible directory.
[error] [client ::1]
[error] [client ::1] Premature end of script headers: something.py

My first thought was “Wow, that’s quite a long way of telling me to ‘just quit.’” Not wanting to concede defeat, I did some quick Google searching to find that the following snippet of Python code would allow me program another day:

import os
os.environ['PYTHON_EGG_CACHE'] = '/tmp'

I’d like to pretend I know what that means but I really don’t know. In any event, if you start receiving those errors, this snippet could be your ticket to taking a bite out of Python.

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Fixing Python’s “Python Eggs” Error

Related posts:

  1. Custom Error Handling in PHP
  2. Custom Error Page Tips – Designate The Pages You Hope No One Sees
  3. PHP, ODBC, and nvarchar
  4. google.load(): Utilize Google’s Ajax Libraries API
  5. Prevent Directory Listings With .htaccess

 
Feb 23rd, 2010 by Barker Design
Create a Simple News Scroller Using MooTools, Part I: The Basics

News Scroller

News scroller have been around forever on the internet. Why? Because they’re usually classy and effective. Over the next few weeks, we’ll be taking a simple scroller and making it into a flexible, portable class. We have to crawl before we walk though; let’s make a simple news scroller using MooTools.

View Demo

The HTML

<div id="news-feed">
	<ul>
		<li><strong style="font-size:14px;">News Item 1</strong><br />Pellentesque habitant morbi...<a href="#">Read More</a></li>
		<li><strong style="font-size:14px;">News Item 2</strong><br />Pellentesque habitant morbi...<a href="/news/2">Read More</a></li>
		<!-- more.... -->
	</ul>
</div>

The HTML part is fairly simple: a list with numerous list items (news items) wrapped in a single DIV.

The CSS

#news-feed	 { height:200px; width:300px; overflow:hidden; position:relative; border:1px solid #ccc; background:#eee; }
#news-feed ul	{ position:absolute; top:0; left:0; list-style-type:none; padding:0; margin:0; }
#news-feed ul li { height:180px; font-size:12px; margin:0; padding:10px; overflow:hidden; }

Getting the CSS correct is very important for our simple scroller. The wrapper DIV must be positioned relative and the UL must be positioned absolutely. Each LI’s height + padding/margin/border must be the same height as the UL itself.

The MooTools Javascript

window.addEvent('domready',function() {
	/* settings */
	var list = $('news-feed').getFirst('ul');
	var items = list.getElements('li');
	var showDuration = 3000;
	var scrollDuration = 500;
	var index = 0;
	var height = items[0].getSize().y;
	/* action func */
	var move = function() {
		list.set('tween',{
			duration: scrollDuration,
			onComplete: function() {
				if(index == items.length - 1) {
					index = 0 - 1;
					list.scrollTo(0,0);
				}
			}
		}).tween('top',0 - (++index * height));
	};
	/* go! */
	window.addEvent('load',function() {
		move.periodical(showDuration);
	});
});

The settings will be placed at the top of the code block, as always. Once the settings are defined, a function is created that scrolls from the current news item to the next news item. Once the scroller reaches the last news item, it scrolls back to the first one. Lastly, when the page has loaded, the directive to start the news scroller is given.

View Demo

Creating a basic scroller is super simple. Look forward to future posts expanding the capabilities of our scroller, including creating a class and adding events.

Don’t forget to follow me on Twitter and be sure to visit Script & Style for the best Javascript and CSS articles around!Sponsor the David Walsh Blog and get your brand in front of several thousand users per day!

Create a Simple News Scroller Using MooTools, Part I: The Basics

Related posts:

  1. MooTools Font-Size Scroller with Cookie Save
  2. Create a Simple Slideshow Using MooTools
  3. Create a Simple Slideshow Using MooTools, Part II: Controls and Events
  4. Create a Simple Slideshow Using MooTools, Part IV: Thumbnails and Captions
  5. Using MooTools 1.2 For Drag, Drop, Sort, Save

 

Authors

» Substance: WordPress » Style: Audacity of Tanish