Snook.ca

Javascript

In working on a Bootstrap-based client project, they needed the heights of all the items to be the same height, even though the content was of different heights.
Bootstrap uses position:absolute to move the items. As such, techniques like flex and grid aren’t of much help here.
The top result on Google as of this writing works but only on one carousel. In an attempt to rewrite the script...

Separation of concerns. You have your HTML over there, your CSS over there, and your JavaScript over there. Each should be as separated and independent as possible. Or so we’re told.
While CSS Zen Garden gave us a glimpse of a possible world where CSS could change and HTML never would, the reality—at least, in my experience—has been much different. Design changes often require both HTML ...

Years ago, I put together a tiny jQuery script for doing a simple slideshow. Due to chaining, it was only a handful of lines. It still needed jQuery, though, which was a 93KB dependency (33KB gzipped).
In the six years since then, browsers have improved their DOM APIs. What would it look like if I tried to write this script now without jQuery and used the DOM APIs along with some handy CSS?
...

Over 4 years ago, I wrote a really simple slideshow script using jQuery. It just took a bunch of images of the same dimensions and cycled through them. The code is only a few lines long (jQuery notwithstanding).
Since that time, however, people have often asked for variations. I've updated the demo page with most requested variations.
Linking the Slides
Sure the images rotated but you kn...

I was making a change to a page that needed to pull from a remote API and make changes to various parts of the page. Sounds like the time to pull out jQuery and Ajax, doesn't it? Instead, I just used old fashioned JavaScript. Actually, I used new fashioned JavaScript.
Browsers haven't stood still in the advent of libraries and frameworks. As a result, we can take advantage of those feature...

Using CSS transitions can be quite fun. But what's not fun is when you want to transition something that needs to use display:none or visibility:hidden (or really, any non-transitionable property).
For example, let's say you have a dialog. When the user clicks on the close button, you want the dialog to fade out — a simple transition from opacity:1 to opacity:0. The problem is that t...

Awhile back, I wrote an article on how to animate background images with jQuery to create some nifty effects. One of the most common questions I receive on that article is, "How do I handle active states?" It is time to answer that question.
There are two ways in which you can handle the active state:
Create a different animation for active elements; or
Change the background ima...

A friend was looking at doing a simple slideshow. The requirements were very straightforward:
No animation controls. eg: play, stop.
Images should cross-fade.
Her instinct was to find an existing jQuery plug-in and revise it to work to her needs. That would seem simple enough but if you do a search for jQuery slideshows, you'll find that there are plenty of them and they are fille...

While at the Fronteers conference watching Thomas Fuchs go through his slides, a keen member of the audience noticed his use of bitwise negation and asked what it was for. Understandable, as there is so rarely a time where bitwise operators seem necessary.
It did, however, remind me of a project that I worked on where I ended up using bitwise operators quite heavily in one particular chunk of c...

In a case of, "I didn't know you could do that," I discovered via some random blog post I've now lost track of, that you can do multi-line JavaScript by escaping the line breaks.
var a = 'You can start here \
and continue here \
and then finish it up here.';
The backslash on each line allows you to keep going. It's a little bit cleaner than opening and closing quotes and a concatena...

The Module Pattern is the use of closures to create, in essence, private functions that are only accessible by other functions created within that closure. Functions can be attached to an object and returned outside of that function call. This establishes a public API and only the functions defined within that public API will have access to those hidden functions.
The YUI blog documents this we...

Now that I have a little more free time, I've begun the process of bringing Snitter back to life. The crowd of desktop applications has not deterred my resolve to (re)build a Twitter application of my own. I have a vision — a vision that I've had since before SXSW of last year — that I still have an opportunity to bring to fruition.
However, along the way, ...

While I've known of Yahoo Pipes for awhile, I never really thought to use it until now. Pipes is a neat tool that Yahoo has put together to allow you to mashup feeds, filter feeds and create a completely new feed.
Commonly, I've seen people take feeds from a number of different sources on a particular subject and combine them into a master feed. For example, they want a master CakePHP feed but ...

That's right folks. It's time for another screencast! This time, I thought it'd be nice to cover a little bit of Firebug. I've actually been meaning to put together a few screencasts on Firebug. If you like this one, definitely let me know and I'll be sure to put some more together.
In this screencast, I take a quick look at how to use breakpoints in Firebug to help in your debugging endeavours. ...

In building this iteration of the blog, I decided to follow that trendiest of trends and embed my latest Twitter status on my sidebar. Despite having been on Twitter for awhile and having my site linked from my Twitter account, I didn't really have anything pushing people from my site back to Twitter.
Problem solved: add status to sidebar. But what's the best way to keep it up to date? I could p...

You have an element and within that element you want an item to be clicked on and set as active. Then you want to click on another item and have it to be set as active. Maybe it's navigation, maybe it's tabs. This is a common pattern. So much so, that I've rewritten this code a few times but keep losing track of it.
This is a jQuery plugin that does the ol' switcheroo and is very simple. When yo...

After reading Dave Shea's article on CSS Sprites using jQuery to produce animation effects, I felt like playing around with things to see what could be done but accomplish it with a simpler HTML structure (no need for adding superfluous tags) and simpler code, too.
Changing the position of the background image felt to be the best approach to creating the type of effect we're looking for (and I'm...

Sometimes it's the small things that can frustrate you. A missing semi-colon, an extra comma. This afternoon, I ran into the invalid script type:
<script type="text/javscript" src="example.js"></script>
If you're more observant than I you'll notice that the second A is missing in javascript. Without a proper MIME type, browsers don't process the script leaving y...

Sometimes we get it in our heads that a task is too complex that we just ignore doing it. That's been my mindset when thinking about developing a plugin for jQuery. I've always thought that some of the code I developed would make more sense as a plugin but I just didn't have time to figure it out.
After finally pushing myself into learning about jQuery plugins, I was left saying, "That's it...

This is an excerpt from my book, Accelerated DOM Scripting available at Amazon and other fine retailers. Although it's only a small section of the book, it's one of my favourite pieces because it had always been a mystery to me.
If you’ve scoured through any number of Ajax solutions, you might have noticed different XMLHttpRequest objects being referred to. Microsoft’s XML implemen...

Safari is building in CSS animations. That's right. With a little bit of CSS, you'll be able to animate obects on the page. The transitions are built using a number of CSS declarations for declaring what properties should change, for how long, and even being able to transform the object like rotations.
Sound cool? I don't think so. Not only does it make CSS more complicated, it makes JavaScript m...

Wow. Over 230 people left a comment to win a copy of Accelerated DOM Scripting. Either people really want to get their hands on it or people just really like free stuff! A few people also had questions about the book and I figured now would be as good a time as any to reply to those.
Questions Answered
I'm thinking of writing a book, too. What software do you use?
Most publishers have a Micro...

Yippeee! My largest writing effort to date has finally come to fruition: Accelerated DOM Scripting with Ajax, APIs, and Libraries published by the fine folks over at Apress.
The book was something that I started last summer after having met the senior editor at the time, Chris Mills, at SXSW. (Chris has since moved on to Opera...the browser, not the musical style!) The writing was slow going and...

In drag and drop situations, there's often a time where an area of the page is within an element with the overflow set to scroll. This is common to display a list of items that would be longer than the rest of the elements on the page. If you're dragging from Section A to Section B, you don't want the user to have to scroll down the page to access the drop point. JPG Magazine is a prime example o...

When a user resizes the browser window, I wanted to resize some elements on the page. So, I attached an onresize event handler to the window. I noticed it rather peculiar when Internet Explorer 6 kept locking up on me.
Turns out, IE6 fires the event even when the document body changes in size. Here's a quick example to demonstrate:
<script type="text/javascript">
var currheight...

I decided to put together a little proof of concept. The idea is to mimic the functionality found in desktop applications like Adobe Photoshop where a user can click on a checkbox and while continuing to hold the mouse down, can move over other checkboxes and have them toggle as well.
I've put together a demo page for Toggler that you can check out and play around with. Because this is a proof o...

I just reported this little nugget to the Firebug bug report. Basically, the problem I ran into was in trying to do some profiling using Firebug to see where my code bottlenecks were occuring. Little did I realize that I was being led astray.
If you're not familiar with using the profile feature, you should be. It's a handy way to see how much time is getting spent in each function. (Maybe I'll d...

Even on the simplest of web pages, we have to handle different states that parts of our document may be in at any time. Probably the most common of which is the simple rollover. Move your mouse over an element and the image changes. This was traditionally done with images and JavaScript until CSS came along and gave us the :hover pseudo class.
What happens when a state needs a little more perman...

Ajaxian posted about Nicolas Faugout's approach to abstract the XMLHttpRequest object.
if (!XMLHttpRequest) {
function XMLHttpRequest() {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
The problem, as pointed out in the comments of that article is that Internet Explorer declares the function before it runs the code. In Firefox (and possibly others), it doesn't. Therefore, it s...

One of the slides in my presentation at Webvisions last year was titled "Avoid Library Calls". The idea behind this was to try and build your code in a way that it didn't need to be tied so deeply to one particular library.
Here's the example I used:
function makeBlack(elementname){
$(elementname).style.color = '#000';
}
function makeBlack(element){
element.style.color = '#0...

This has bitten me a couple times now and I feel like an idiot every time it happens. If you don't close your tags properly and you need to access elements via the DOM, expect trouble in Internet Explorer.
I do most of my testing in Firefox which has been very forgiving and as a result, I'll get to the point where when I switch to test in IE, the browser throws an error and worse, won't even ren...

Way back when I first implemented the fixed comments, I used JavaScript to duplicate the effect in Internet Explorer 6. It was really choppy but it worked. This type of script has been around since the Age of DHTML but I still get the occasional person asking how this was done. So here's the original code I had:
function window_onscroll()
{
var el = document.getElementById('postcomment');
...

I've come to depend on Firebug so much that I left behind a couple console.log messages while testing a project. Problem was, with Firebug disabled (or not installed as was the case with a client), the application was failing. Looking at the code, nothing seemed out of place. I tried disabling Firebug and true enough, it stopped working. Took me a couple minutes to realize the debug code was getti...

As a JavaScript developer, you are in many ways an environmentalist. JavaScript is a language unlike most other languages. For when it comes to JavaScript development, we must consider the mantra of the environmentalist: Reduce, reuse, recycle.
Reduce
When developing server-side, we have flexibility. For the most part, whatever code isn't executed, is simply hard drive filler. It doesn't affect ...

In the same vein as the Prototype Cheat Sheet, I decided to go through and detail the Mootools library, as well. In comparison to Prototype, Mootools is definitely smaller and it's obvious they've put more focus on interactivity and decent DOM traversing.
I've colour-coded this one to match the four main categories that are in the download section of the web site and within the documentation. Th...

I've gone through and detailed the methods and properties of each of the modules within the Prototype JavaScript library.
I decided to revisit the cheat sheet. A couple people had been asking about it and with the final release of 1.5.0 just around the corner, now seemed as a good a time as any. I've done things a little differently this time. The first time around, I really just wanted to see ...

In many of the JavaScript tutorials, there's plenty of concern over this. The this keyword is used to reference the current function/object context. The problem is, a function can easily be 'detached' from the object it was originally defined as a method of. As a result, the this keyword no longer references what you thought it should and errors occur.
var obj = {
myProperty: 5,
myMethod:...

After covering the basics of a drag and drop, it's time to look at detecting things we're dragging over. When it comes to a drag and drop, you normally want to have something to drop onto. Otherwise, just dragging an item around the screen can get boring. You want to interact with the page somehow. You might want to drag items into a shopping cart, or sort a list of items, or dock some widget on...

The mechanics of a drag and drop are pretty interesting and most library implementations do similar things, albeit to various extents. As I explain the inner workings, I'll touch on Yahoo's, Mootools', and Script.aculo.us' implementations, what to expect, and how they differ.
A drag and drop essentially consists of a few events (and by events, I mean, moments in time, not DOM events). There's th...

It almost sounds like the beginning of a joke...("Safari, Display:none and getComputedStyle walk into a bar..."). Anyways, I just ran into this and thought I'd share.
In Safari 2.0.4 (419.3), you can't use getComputedStyle on an element that has display set to none. It's like the element doesn't even exist. Luckily, the latest Webkit builds have fixed this little niggle.
For a quick test case, c...

Previously, I had asked Which is Better, using var o = new function(){...} or var o = function(){..}();. At the time, it really just seemed to fall on personal preference. Both seemed to create singletons. It's just that some people like to do it one way while others perfer to do it the other way.
A commenter on my recent article at Digital Web, Objectifying JavaScript, however, pointed out tha...

Could the Apple iTunes Store soon have a fully public API? On Apple's iTunes page, they have a search widget featured in the sidebar. What's interesting is that this AJAX-powered widget is returning a JSON object. How very API friendly!
The script located at http://www.apple.com/itunes/scripts/itmsSearch.php currently accepts two parameters, searchTerm and searchType where the type is one of al...

This example is outdated and will not work with Mootools 1.0.
So, without an actual demo to play around with, I thought I'd put one together, both to see how easy it'd be to work with and to help demonstrate to others what to expect. What a better example than the drag and drop (especially since I'm finishing up a project that just happened to use drag and drop). Check out the example and check...

The folks behind the popular moo.fx have gone and released their own JavaScript library called mootools, attempting to take the best of JQuery and the best of Prototype. The mad4milk team have the announcement on their blog.
Probably one of the nicest features so far is the download page. Select the components that you need and dependencies will automatically be calculated for you. You also have ...

Ever have an IF statement that has a whole bunch of OR (||) statements that keep testing a variable against a bunch of values?
if(name == 'bobby' || name == 'sue' || name == 'smith') { ... }
In JavaScript, there's an in operator that tests whether a property is in an object. We can actually use this to mimic the PHP function in_array.
if(name in {'bobby':'', 'sue':'','smith':''}) { ... }
...

Here's a quick way to add all the Element methods to a DOM element using Prototype 1.5 (I believe the RC is right around the corner if not already here).
var div = document.createElement('div');
Element.extend(div);
That's it. Then you can do things like div.show() or div.hide(). Well, you still need to append the DIV to the document but you get the idea.
...

Just thought I'd throw this question out to the crowd.
var obj = new function(){ ... };
// OR
var obj = function(){...}();
I prefer the former to the latter because I can assign properties to the object without explicitly having to return an object but I noticed Dustin Diaz did the latter in his latest screencast.
Hands up if this kind of JavaScript minutia just put you to sleep.
...

A new post on the IEBlog has some decent tips on optimizing the performance of your scripts. Although written specifically addressing performance issues as they relate to Internet Explorer, I suspect most of the suggestions would appy to other browsers as well.
The summary of the article, the first of a three part series, is to:
Declare var for variables that are meant to have local scope
Cache...

Here are a few of the most popular ways to do cross domain calls via JavaScript: proxies, JSON, and Flash.
Cross domain proxy
This is one of the most common approaches. Your script calls your server, your server makes the call to the remote server and then returns the result back to the client. There are some definite advantages to this approach: you have more control over the entire lifecycle. Yo...

WIth a lot of talk about JSON these days, it's important to understand the syntax and how it differs from the object literal — or rather how it's a subset of it.
The object literal is encapsulated by curly brackets with zero or more property and value pairs separated by commas. Each property and value is separated by a colon. Property names can be an identifier, a string, or a number.
Synt...

Dan Rubin made comment on an implementation of Edit in Place I had linked to:
"I'm stumped about how one would further optimize or improve (Edit in Place), but I'm also curious: would you improve it, and how?"
What's interesting is that there are two aspects where improvements can occur: implementation and design.
Improving Implementation
By implementation, I mean, how has the developer put it...

Some of you may be aware of S5: the Simple Standards-based Slide Show System from Eric Meyer. It's a simple combination of HTML, CSS and JavaScript for creating slideshows. No Powerpoint required.
S5key, is a Keynote-inspired addition that offers up some additional functionality. Now, I say "inspired" because to be honest, I've never used Keynote. The screenshots, however, looked neat and felt ...

The idea of creating JavaScript namespaces are coming up more and more. With the expanded use of OPC (Other People's Code &mdash "you down with OPC?"), the idea of using or taking advantage of JavaScript namespaces is coming up more and more.
What is a JavaScript namespace?
More importantly, "what is a namespace?" A namespace is a container and allows you to bundle up all your functionality ...

It's happened. I suppose it probably happened the instant the acronym itself was coined but AJAX isn't just AJAX any more. It's Ajax. (No, not the place outside of Toronto. Um, no, not the cleaning stuff, either.) Notice the uppercase A with the all the other lowercase letters. (Through second-hand knowledge, I'm attributing this distinction to Jeremy Keith — He can prove me wrong.)
That's ...

In the redesign, I thought long and hard about how to approach a number of issues. My solution was to implement microwidgets. Yes, I'm even giving them a name. For example, I knew going dark would annoy some people so I did the contrast microwidget (which incidentally has changed slightly from launch to be a little more obvious). The microwidgets are a combination of JavaScript and CSS and were fa...

I know Jeremy Keith's position on this but I still don't understand why him and others are so against innerHTML. Sure it's not part of a standard (yet) but neither is the XMLHttpRequest object (yet).
When you have something that is faster and easier, why wouldn't you use it?
Some have argued that it creates the potential for generating invalid markup but no more or less than creating invalid mar...

Ajaxian covers a post on logging client-side errors on the server-side using AJAX. A commenter made mention of inconsistent behaviour when using the onerror event as detailed on PPK.
In determining the issue, I noticed what appeared to be the issue and left the following comment on Ajaxian:
For example, trying to run myfunction() where myfunction doesn't exist will trigger onerror. But running m...

One of my biggest peeves of Prototype was the singleton nature of the Element object. Doing Element.hide('myelement') just didn't feel right. Justin of Encytemedia has highlighted the recent updates which now allow for the much more elegant $('myelement').hide(). You'll need to download the latest version of Prototype (currently/still 1.5.0_pre0).
Justin also demonstrates the ability to extend th...

I have since updated these cheat sheets.
In getting to know Prototype a little better, I decided to go through the latest version of the Prototype library (1.5.0_pre0) and detail every method and property that was available. In doing so, I got a much better understanding of how the code works. Here are the files in a 1280x960 and a widescreen 1440x900 version.
1280x960
1440x900
1280x960...

In JavaScript, we have functions and we
have arguments that we pass into those functions. But how JavaScript handles
what you’re passing in is not always clear. When you start getting into
object-oriented development, you may find yourself perplexed over why you have
access to values sometimes but not other times.
When passing in a primitive type variable
like a string or a number, the valu...

Over at Ajaxian, they've offered up a useful tip for dealing with code that exists in the global namespace and is conflicting with other scripts: move it into its own function. Example:
(function() {
// do you stuff here!
})();
What's the global namespace? That's the window object. Any time you instantiate a global variable, it is automatically part of the window object.
var myvar = 5;
alert(...

I jest. I just think it's interesting that people have taken the time to create an acronym and development process for something that everybody has been calling AJAX anyways. AHAH is Asychronous HTML and HTTP. HTML gets pregenerated on the server and then spit into the DOM via innerHTML. This is how I've always approached it. It just seemed so much easier and faster on the client side. As the team...

They're becoming all the rage: easy-to-use libraries that can make your application look sexy. Here's a short list to help you out:
moo.fx
Moo.fx is the newest one on the block and boasts a small 3KB footprint. Ignore for a minute that you need the 27KB footprint of Prototype to go along with that. All snarkiness aside, Prototype actually has a number of classes built into it that aren't required...

After seeing a couple of my recent experiments mislabeled as AJAX-enabled, I think some explanation is in order.
What is AJAX?
AJAX is a new term coined just four short months ago by the folks over at Adaptive Path. I suggest you give it a read if you haven’t already. As they explain, AJAX stands for Asynchronous JavaScript And XML.
At the core of all this is XMLHttpRequest. It allows a c...

Niggle’s recent entry on good design, bad design touches on the usability of drop down date selection. Now, as any web developer who has had to put together a form with date selection will know, it is one of the most difficult things to achieve.
Some (and I do this, too) simply have three inputs — one for year, one for day, and one for month. They might be text boxes or they might be ...

There's a variety of scripts out there for getElementsByClassName. Oddly though, the first 20 or so results from Google are confusing or completely inaccurate. So, what's your favourite getElementsByClassName script?
Here's something I threw together based on an unusable script I just saw on Digital Media Minute.
function getElementsByClassName(node, classname)
{
var a = [];
var re = new...

One of the recurring requests out of the fixed commenting system was the ability to point to a comment and quote from that post. While I haven't had the time to get that functionality together for my own blog, I had been asked by Jacob G. (of recent CSSVault fame) to put together a new design for a series of blogs that he had or wanted to put together [See Fun Money Blog, CPVault, and Filmsy].
O...

As many of you have seen with the redesign and the fixed comments, I've really tried to increase the usability of the comments. Why so much focus on the comments? Because your interaction is a critical part of why I run this site. Your insights and assistance are an asset to me and to anybody else who happens to come across these pages.
In my next step in building a better experience and upon th...

Every tutorial that I've seen describes that to create a global variable you have to declare it outside the function.
var myvar = 5;
function myFunction()
alert(myvar); // 5
}
And this is the way I've been doing it for years. The problem is, I've never been particularly happy about this. It never felt self contained. Then I thought, "Hey, why not just attach it to the window object?" I almost...

brothercake puts together a great script for detecting the availability of objects while the page loads. This way, you don't have to wait until the window.onload event to access elements on the page.
...

In continuation of my experimentation with position:fixed from yesterday, I decided to try and enhance the form slightly by having it check to see how close the comment form was to the top of the page. If it got too high, I'd change from position:absolute to position:fixed like I did yesterday.
This should certainly resolve the issue for those at a resolution of 1024 by 768 that weren't able to f...

Internet Explorer has a bug where wrapping a label around an image doesn't work the same as if you wrap it around text.
Example:
<input type="checkbox" id="a"><label for="a"><img src="..."></label>
What the label does is create an association between its contents and a control on the page. In most browsers, clicking on text or an image within the label will give focu...

Ever write some javascript and find typing =true or =false just way too time consuming? Why not rely on some boolean assignment operators to do the trick? To make something true, use |=1. To make something false, use &=0.
How and why does this work? Let's take a look at each one seperately. In the true example, we have |=1. What this basically means is take the value on the left of operator and p...

Javascript "uses" the variable, even if it's declared in an if statement. Most people probably won't run into this. I only did by accident in trying to get some cross-browser stuff working. Here's an example:
var i=5;
function test(){
var a;
if(a==0){var i=5;}
alert(i);
}
Would you expect it to alert 5? In fact, it alerts as undefined. Even though the code within the if statement never get...

I just tried a quick test to see which of two regular expression techniques would perform better. I was quite surprised to find that different browsers gave me different results for different techniques. Now, this is in no way a truly scientific result and I'd be interested to see how it plays out on multiple systems and on multiple browsers.
I put together the following code to test my two metho...

To recap, I wanted some unobtrusive JavaScript that would automatically strip any link that was pointing to the current page. The problem with the first version was that initially, I didn't take anchors into account. A link to a page with an anchor was considered a different URL than one with an anchor. Then next step was to strip the links of all URLs that pointed to the current page regardless o...

After reading through how to turn off current page links using CSS on The Man in Blue, I decided to put together a way to accomplish the same using JavaScript.
The technique would be straightforward: loop through all the links on the page and remove the tag if it's the same as the current page. The problem is that the W3C DOM doesn't seem to have a way of removing the current node while retaining...

When programming in scripting languages such as JavaScript or ActionScript, we store values directly in a variable or often in an array. While bitwise operations are often relegated for use in higher-level programming languages such as C++, there are advantages to using them in scripting languages as well.
The premise behind storing values at the bit level is quite straightfoward. We simply store...

Sometimes in JavaScript, you may want to redirect a user to another URL. This is often done setting the window.location properly like so:
window.location = "https://snook.ca/';
However, Safari and IE 5.2 for Mac (at least on OSX) behave a little differently than browsers on the PC. I put together this basic test page in order to see which scenarios work and which don't.
<script type="text/ja...

Any person who programs in JavaScript is quite familiar with the 'if...else' statement and likely aware of the 'expression ? true : false' format. While the second format is smaller, there is another key advantage over the 'if' statement: it can be embedded into another statement. This can help reduce excessive 'if' statements when the logic contained within them is repetitive.
For example:
if (ap...

I did some research and found that not many people had detailed a solution to do this so I've created my own solution. First, there's a couple things that you need to be aware of before you proceed.
This is a client-based solution and therefore your client must have Microsoft Word installed on their machine.
This solution accesses files on the client's machine and therefore your client must hav...