subCHILD

Archive for the Code category

Slideshowify Gets a Project Homepage, Demos, Documentation

posted by admin in Code, CSS, design, HTML, JavaScript, jQuery, jQuery

After just sitting there collecting dust for a while, Slideshowify is back and better than ever.

New updates include CSS3 support (provided via @rstacruz‘s excellent jquery.transit.js plugin), animation as well as zooming in both directions and better browser support – it works and looks great on tablets and other touch devices.

In addition, the project now has a legitimate project homepage which provides documentation and a couple of live demos. 

Check it out now at: http://subchild.com/slideshowify

iStockutils.com – Built with Flask and Now Live

I recently set out to learn Python, specifically on the Flask (+Werkzeug/Jinja2) microframework, and did so through developing a tool for iStocphoto.com contributors. The result is iStockutils.com, and the code is available for viewing/forking on GitHub.

I still have much more to learn, but though this exercise I’ve become a big fan of Python and, after working with lots of different templating engines over the years, really like the format and flexibility of Jinja2. Kudos to Armin Ronacher for his fantastic work on all of this.

No kudos though to the iStockphoto folks who haven’t even responded to my request for access to their API. This means that all of the data is currently scraped from the HTML. Nasty.

Processing XML with jQuery – An IBM devWorks Tutorial

posted by admin in Code, JavaScript, jQuery, jQuery, PHP, XML

My tutorial on processing XML with jQuery in the browser is now live on IBM’s developerWorks website. Check it out at:

http://www.ibm.com/developerworks/xml/tutorials/x-processxmljquerytut/index.html

Most JavaScript and jQuery ninjas needn’t read past the title for the gist, but hopefully there’s something new for everyone. Either way, your comments are welcome.

Amazon CloudFront – PHP Invalidator

posted by admin in PHP, XML

cloudfrontlogoAmazon recently (finally!) added support for invalidation to CloudFront.  Frankly, without this feature the service was pretty useless to me since updating (or deleting) the cached resource would mean that the actual operation would take up to 24 hours to be reflected on the CDN.  But all is well now as the invalidation API available and is, as expected, very responsive.  (Based on initial tests, invalidations take a few minutes to process.)

What was missing though is a PHP API for easily creating and processing invalidation requests, so I put one together, largely inspired by the existing S3 and CloudFront PHP kits.



To invalidate an object, just create an instance of CloudFront and call invalidate() it. Like so:

$cf = new CloudFront($keyId, $secretKey, $distributionId);

// invalidate single object
$cf->invalidate("/path/to/object");

// invalidate many objects with single (batch) request
$cf->invalidate(array("/path/to/first","/path/to/second"));

// enable debugging (response output) by passing true as the second argument
$cf->invalidate(array("/path/to/first","/path/to/second"), true);

Check out the source on GitHub: http://github.com/subchild/CloudFront-PHP-Invalidator

A couple of things to keep in mind. CloudFront supports very few concurrent invalidation requests so make batch requests as much as possible.  If you absolutely need to up this limit, go to http://aws.amazon.com/cloudfront-request/ and submit such a request. Also, keep in mind that updating a resource on CloudFront means that you’ll need to update it on S3 first, then invalidate the CloudFront copy only after the S3 has actually been updated, not when you make the request.

Live XML Editor: Version 1.5

posted by admin in JavaScript, jQuery, PHP, XML
liveXmlEdit_screenshot

I recently had a chance to make a few updates to the Live XML Editor and address some user requests. Version 1.5 is now done and out.  Among the updates are:

- jQuery 1.4 support. Since the editor relies heavily on DOM rendering and events, this update makes the app snappier.

- Comment node display and editing. This was requested by a user and I was surprised that I hadn’t thought of it. Creating comments isn’t supported yet, but its on the to-do list.

- Various bug fixes, tweaks and optimizations.

- Added (MIT) license.

Check it out: http://www.subchild.com/liveXmlEdit.  Code is also on GitHub: http://github.com/subchild/liveXmlEdit/

Make an Object loggable()

posted by admin in JavaScript

loggable() is a simple little function for safely making a JavaScript object (console) loggable. (Name was inspired by @furf‘s jquery.bindable.js.)

/**
 * Loggable adds a log method to the passed object.
 * @param obj       {Object}  Object which will get a new log() method
 * @param objName   {String}  Optional parameter for displaying a string before each log output
 * @param debugMode {boolean} Optional switch for disabling logging
 */
function loggable(obj /* , objName, debugMode */){
	var objName   = arguments[1] || "",
		debugMode = (typeof arguments[2]!=="undefined") ? arguments[2] : true,
		prefix    = objName ? objName + ": " : "";
	obj.log = (function(prefix){
		return function(){
			if (debugMode && typeof console!=="undefined"){
				if (arguments.length){
					arguments[0] = prefix + arguments[0];
				}
				console.log.apply(null, arguments);
			}
		}
	})(prefix);
	return obj;
};

So if you have an object like:

var obj = {
  name     : "Alex",
  getName : function(){ return "Alex" },
  setName : function(name){
    obj.name = name;
    obj.log("name was set to", name);
  }
}

loggable(obj, "Obj");

Then, executing:

obj.setName("Balthazar");

Will log this in your console (Firebug or otherwise):

Obj: name was set to Balthazar.

Here it is on GitHub: http://gist.github.com/547926

Slideshowify: Ken Burns Slideshow Effect as a jQuery Plugin

Slideshowify is a jQuery plugin for creating a slideshow of images that will fill the screen with a (cropped) image, then pan across to reveal the rest of it. This is commonly referred to as the Ken Burns Effect and is often seen in documentaries. A nice version is of it can be seen in that Mac screensaver.

Anyhow, here’s a stab at such a thing. Some future enhancements are obvious (pan direction, zooming, transition options, etc.) and anticipate finding the time to add that stuff shortly.

For now, check out the code on github.com and see a demo at www.subchild.com/slideshowify

To use it, include jQuery, jquery.slideshowify.js, then feed slideshowify a selector that matches some images. For example:

$("img").slideshowify();

Alternatively, you could load data from an external feed and call $.slideshowify() with configuration options:

$.slideshowify({
 	dataUrl   : "http://www.gallerama.com/services/gallery/get.php?gid=2107&versions[]=9",
	dataType  : "jsonp",
	randomize : true,
 	filterFn  : function(imgs){
 		var fixedImgs = [];
 		$.each(imgs, function(i, img){
 			fixedImgs.push(img.versions["9"]);
 		});
 		return fixedImgs;
 	},
	afterFadeIn : function(imgData){},
	beforeFadeOut : function(imgData){}
 });

Most of the params here are passed directly to jQuery’s $.ajax() method. Some are used to reformat the data (slideshowify() expects an array of objects of this format: {src:”domain.com/path/to/image.jpg”, w:”600″, h:”400″}), others are hooks or speed (fade, delay) options.

Proper documentation will be provided. Most likely.

Sorting a JSON Array by Property

posted by admin in Code, JavaScript

Sorting arrays of JSON objects is a task that I occasionally come across. Here’s a little utility I’ve been using for a while that does the trick.

/**
 * Sorts an array of json objects by some common property, or sub-property.
 * @param {array} objArray
 * @param {array|string} prop Dot-delimited string or array of (sub)properties
 */
function sortJsonArrayByProp(objArray, prop){
	if (arguments.length<2){
		throw new Error("sortJsonArrayByProp requires 2 arguments");
	}
	if (objArray &amp;&amp; objArray.constructor===Array){
		var propPath = (prop.constructor===Array) ? prop : prop.split(".");
		objArray.sort(function(a,b){
			for (var p in propPath){
				if (a[propPath[p]] &amp;&amp; b[propPath[p]]){
					a = a[propPath[p]];
					b = b[propPath[p]];
				}
			}
			// convert numeric strings to integers
			a = a.match(/^\d+$/) ? +a : a;
			b = b.match(/^\d+$/) ? +b : b;
			return ( (a < b) ? -1 : ((a > b) ? 1 : 0) );
		});
	}
}

Here’s a simple example:

var arr = [
	{name:"Zack", friends:{count:50}},
	{name:"Alex", friends:{count:80}},
	{name:"Mike", friends:{count:30}}
];
sortJsonArrayByProp(arr, "name");
sortJsonArrayByProp(arr, "friends.count");
sortJsonArrayByProp(arr, ["friends","count"]);

[Update] This function now converts strings made up entirely of digits into integers for (presumably) more accurate comparisons, and therefore, sorting.

The "MS Shell Dlg" Mystery (Solved)

posted by admin in browsers, CSS, design, fonts, HTML

If you haven’t noticed (and are using a PC), the headlines on this blog should now be rendered using the MS Shell Dlg font [I've since changed this and have been experimenting with custom fonts via @font-face, but all information in this post still applies otherwise.] I learned about this font just now after trying to figure out why tadalist.com‘s input fields were rendering using it instead of the fonts specified in the CSS rule. I’m still unsure why the computed style lists MS Shell Dlg as the font since its never explicitly specified nor is the the default, but it is. (If you know why this is, drop a comment below.)

Anyhow, I really like the way this font looks at 20+ pixels and bolded, so its the new style for the (H2) headers. If you’re on a Mac, you should see Helvetica and since that font carries mad clout complaints will be appropriately ignored.

OK, I’m off to read more about this, starting here: http://support.microsoft.com/kb/282187

Update #1

Just read it.  A very intriguing quote from that page: “It is not a font but a face name for a nonexistent font.”  What?  Its definitely a font and after testing all of the usual suspects, I’m still unsure which one. Bizarre.

Update #2

I found the answer on this page: http://msdn.microsoft.com/en-us/library/dd374112%28VS.85%29.aspx.  The font that MS Shell Dlg maps to on all versions of Windows since Windows 2000 is “Microsoft Sans Serif”.  But I’m guessing that using MS Shell Dlg in the CSS rule instead makes more sense since it will map properly on other versions of Windows, and since its a shorter rule.  Though, specifying “Microsoft Sans Serif” explicitly, followed by more common fonts would make for a better rule and ensure no further surprises.

All this said, I’m still not sure why tadalist.com’s input fields are rendering in this font.

Update #3

Since writing this post, I’m noticing this font substitution taking place more often.  For example, Twitter‘s login input fields behave the same way, as does the h2 tag on Dictionary.com.  What all of these have in common is that they specify the first font name in quotes (presumably since it contains multiple words) and it happens to be a font that I don’t have installed.  While quotes should be permitted in such cases and are even encouraged by some, I find that its not necessary and here appears to not have the intended effect.

SWFUpload Doesn't Work with Windows 7

posted by admin in Flash, JavaScript

Uploading files using a browser has never been ideal, partly since JavaScript and/or HTML do not have the privilege to read size of files on the local file system which stands in the way of calculating upload progress and informing the user with a standard progress bar. To get around this, you can use a Java applet, one of the many hacks which involve Perl, PHP/CLI, or the awesome and very customizable SWFUpload. However, as a new Windows 7 user, I discovered that SWFUpload immediately reports 100% completion and the progress reporting fails. I’m guessing the problem is related to Windows 7′s restrictive nature and a new restrictions on flash plugin’s access to the file system, but hopefully the problem is solvable.

In the meantime, its assuring that the uploads using SWFUpload do work, only the reporting part doesn’t, but that’s the whole reason for using it. The problem was reported on the SWFUpload forum and hopefully its being looked into.

Recent Posts
Recent Comments
About
Simon: Hi there, i am looking for a parameter which can change direction of mov...
CM: Hi, Alex! I know exactly what king of messages you get, like "Hi, I'm new to php a...
admin: Alive and well....
SJ: If the array size exceeded 10 then sorting will not work. any help?...
shutterstock: I've learn several excellent stuff here. Definitely price bookmarking for revisiting....

Subchild is a blog about web development. It's author is Aleksandar Kolundzija, himself a web developer for 10++ years, presently a Hacker-in-Residence at betaworks. Prior to betaworks, Alex worked at Google, Meebo, MLB Advanced Media (MLB.com), Razorfish, and elsewhere.

Some of Alex's side projects include Gallerama.com, Slideshowify, LiveXmlEdit, and other blogs like Dopevector and blog.gallerama.com. When he's not working on any of those, Alex is probably playing guitar, producing music, mixing records, taking photos, playing with his kid, or watching documentaries about particle physics, the monetary system, etc.

Let him know what's up: ak @ subchild.com