The Best addClass and removeClass solution

Posted by
admin
.

Until we can safely assume all browsers have the javascript element.classList property (IE10 has it, and DOM3 compliant browsers have it, so this will be the case if you want to forget about IE9 and below) it's useful to have a quick solution to add and remove a single class from an element. Presumably you are aware that DOM elements can have multiple classes, yet somehow, until recently, the only way to manipulate classes was with the .className property. document.getElementById(...).className = "foo bar"; This is pretty sad. Putting a space between a single property to tell it you want to add two classes is... weaksauce. Obviously jQuery gives you an addClass method that you should use if you have it, but Stack Overflow is amazing and I've stumbled across this great answer: Change an element's CSS class with JavaScript

That answer right there is an example of Stack Overflow's strengths. It's like a wiki for code snippets, and the community identified the bugs until it became a pretty robust, attractive answer. Their answer isn't general enough for me though, as I'd like a function taking parameters to do it:

function removeClass(ele, className) { ele.className = ele.className.replace( new RegExp('(?:^|\\s)' + className + '(?!\\S)', 'g') , '' ); }

Works pretty well.

Oldschool Event Listeners

Posted by
admin
.

Frameworks - specifically jQuery - have changed the nature of coding javascript for web interfaces and ramped up productivity for all web developers. What used to take days to accomplish now takes minutes. As I see it, a framework like jQuery does at least three slightly different, valuable things - it prevents us from having to reinvent the wheel every time we need one; it plasters over browser differences so we don't have to learn them; and it gives us a uniform API for referencing what we need.

Including a "whole framework" (as if jQuery is big) just to solve one problem is sometimes denounced as overkill - just look at some Stack Overflow questions on javascript and you're sure to find arguing back and forth about how questions about vanilla javascript should not have "use jQuery" as a solution. I sympathise with this line of reasoning. If I want to find out how to climb the DOM tree on my own, I don't need someone piping in to tell me I can use jQuery's .parent() function to do that. Using .parent teaches me nothing about core javascript handling of DOM elements and how to traverse them.

It's with this mindset that recently approached a problem in which I wanted to move some inline onclick event handlers to use DOM2's addEventListener. The project, now several years old, uses vanilla javascript and has its own show/hide functions, and I didn't want to add jQuery to it just for .on(whatever). And so I was led down a journey I almost wish I hadn't taken, discovering and reinventing wheels that have already been invented, just to provide support for IE8, which, unsurprisingly, doesn't support addEventListener, and instead uses their own AttachEvent method.

How hard could it be? I'll just do a check for addEventListener and, if it's undefined, use AttachEvent. Googling it returns some code that does this in about 5 lines. Problem solved, right?

Problem solved until I finished the code, and realized that IE's AttachEvent also has a nice way of re-binding the same function multiple times if you tell it to. Normally this wouldn't matter, but I was calling the bind on window resize, which meant that every time I resized my browser window, the bindings would pile on top of eachother. How can I force IE to bind an event only once?

Tired of testing out my own solutions, and satisfied that I wasn't going to learn anything useful building more code to solve this problem, I googled for answers and found one answer suggesting what would have been my best brute-force solution. Store a list of all the function and handler combinations called, and use that list to avoid re-applying handlers. A little lengthy, possibly a little memeory intensive if you're using an old IE and lots of handlers, but easy to understand and use.

But there has to be something better. jQuery's done it, after all, and with some clever namespacing options to reference your handlers if you need to unbind them.

My own half-done solution started along the lines of assinging the function as a porperty of the element, and then I found this great solution by John Resig.

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
	obj['e'+type+fn] = fn;
	obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
	obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
	obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
	obj.detachEvent( 'on'+type, obj[type+fn] );
	obj[type+fn] = null;
  } else
	obj.removeEventListener( type, fn, false );
}
			

Also see this discussion on quirksmode for more details and alternatives.

This solution is elegant and simple, and robust enough. John explains it on his page, but the key is that "obj['e'+type+fn] = fn;" assigns the function as a property of the element. Why? Two reasons. First, so that the line following it, "obj[type+fn] = function(){obj['e'+type+fn]( window.event );}" can reference it using a closure. Second, so we can remove it later if we want.

Learning to use tricks like this to assign a function to an element, and then trapping that assigned function in a closure, are not things you'll learn by taking jQuery shortcuts. It's valuable knowledge.

Then again, productivity is valuable, too. Several hours of learning, versus a few minutes of jQuery. At least these days we have a choice.

Javascript Closures and Continuation Processing

Posted by
admin
.

I’ve been coding javascript for a few years now. Primarily I’ve experimented with it for fun or done some basic essential form validation scripts, but nothing to really test the power of the language (and it is a beautifully flexible language) until I was required to do some page interactivity for a job. I did what many people do and turned to jQuery because frankly there are some effects in jQuery that are too time consuming to do traditionally. If you know javascript and haven’t tried jQuery, you’re living under a rock and have some catching up to do. Don’t worry though, the reason everyone loves jQuery is because it’s so damned easy.

Anyway, jQuery has some magic under the hood that does all sorts of things for you. It’s a crutch, and other than using it I haven’t expanded on my javascript skills in ages. That’s why this tutorial by Nathan Whitehead on javascript closures was like a holy grail to me. It was quick, fun to do, and most importantly it taught me something new about the language. Actually it taught me several new things, many of them about style and how to view functions in more abstract terms. I already knew functions, classes, and everything else in javascript were objects, but I never played with them or saw much use for it.

Continuation passing and closure were both completely new. I thought I had passed the point when a tutorial would be useful for me, but Nathan found something worth teaching and props to him for sharing his knowledge in such an accessible way.

Google+ Impressions and What’s Wrong with Facebook

Posted by
admin
.

It’s been a few weeks now since the explosive (among tech geeks anyway) debut of Google+. It seems people fall into one of 4 categories: those who don’t see anything wrong with Facebook, those who are beholden to Facebook because of their friends, those who flocked to Google+ as soon as possible, and those who don’t care because they don’t use social networking.

The latter group is a dwindling minority among people online because “social networking” has gone from a cute way to augment one’s social identity and perhaps substitute a genuine social life to a general concept that is far more practical. Rather than being merely a social identity, it augments email, texting, an address book, and even (with Google voice and now Skype on Facebook) voice communication. It’s less about showing off and goofing off, and more about pragmatic ways to communicate with people.

This is where Google+ has an advantage over Facebook. Facebook has abysmal user satisfaction which is blamed on “privacy concerns, frequent changes to the Web site, and commercialization and advertising” and which I blame on a scatterbrained interface and outdated design choices. Facebook feels immature and unprofessional, and observing their changes and “enhancements” over the years has been like watching a confused animal flail around in its cage. Or, more accurately, watching a company with poor organization and interface design standards attempt to retain users through gimmicks and monetization schemes. Using Facebook requires practice at figuring out what little icons mean and what obscure settings page contains the menu options for particular features. Photo albums are difficult to reorganize, different pages duplicate nearly the same content, and features get added with a disregard for usability (viewing photos in their new lightbox-style viewer makes right-clicking to get the URL impossible). On top of this they have reorganized everything more than once without making anything easier to find – it’s more like a game of hide and seek.

The only thing Facebook makes it easy to do is talk to people on their walls, poke people, and generally goof around. Many people accept this because this is all they expect to be able to do. It is often said among circles I talk to that they use Facebook because that’s where the girls are (implying that girls are less tech savvy – something I won’t debate here). Some of us, however, see potential for much more.

Facebook relies on its critical mass of users to keep its momentum going and until now nobody has issued a significant challenge to them. It does not, however, cater to professionals or power users, or people who appreciate a clean interface and simplicity. It’s a toy, not a tool.

4 columns, about 50 thumbnail sized images, 2 navigation menus with sub-menus… What the hell am I supposed to be looking at here?

As I see it, Google+ is gearing up to be more of a tool. The first and most obvious aspect of this is that in Google+ you can control who sees what you post. There are too many nightmarish stories about companies investigating people’s Facebook habits and not hiring, or even firing them over a post intended for friends. There is no fine grained control over who you’re talking to (actually there is some control buried in their ‘groups’ which most people don’t use because it’s confusing and tedious) nor is there any control over who can view photos you post. You can forget posting pictures about your drunken antics or ranting about how you hate kittens if you have anyone important on your friends list. Google+ has “circles” to give you at least some ability to segregate your social circles. You can have conversations with a group of people you trust while excluding those you don’t.

Sharing photos is leagues beyond Facebook’s clunky interface for managing albums. Anyone who takes their photography seriously will find this appealing, especially if they routinely have to upload lots of pictures and want to share them with people outside of Facebook. Picasa is a tool for sharing photos in general, not a toy relegated to showing other Facebook friends what you’re up to.

The chat functions for both clients are almost the same for exchanging text (though Google has a leg up by integrating it with Android and Gmail) but Google’s voice chat is very well integrated and battle tested while Facebook only recently acquired Skype and is in the process of integrating it with theirs. Google+ hangouts can be used for conference calling and if Google realizes this and adds more video conferencing options such as the ability to show your desktop to others this could be a professional tool. For face-to-face talking with friends, though, it’s already better than Skype.

Beyond this is the possibility for integration with other Google technologies (such as Google docs) that have been geared towards businesses and that have not been traditionally part of “social networking” (read: Facebook). If Google takes advantage of their strengths in this area, they will have a product that is simply more practical than Facebook for many people.

Finally I have one last point to make regarding the difference between the two: the social crowds in each of them is different. The kinds of people one finds in each site are already well defined, and this is going to continue for some time. Despite Google+ being more of a “tool”, it’s still a way to define your identity, like driving a certain type of car. I don’t want to be seen in a Facebook (a sparkly blue Honda civic with an over-sized spoiler) when I could be cruising around in a Google+ (a Prius?). I expect to see more tech savvy people in Google+, but less “hot chicks” spamming photos of their night club activities. I’m actually OK with that.

Google Apache Page Speed Optimizer

Posted by
admin
.

Google has released a module for Apache that, if it does what they claim, sounds like something everyone running Apache should get (of course it probably won’t come shipped standard due to the inevitably possible compatibility issues that can arise from the type of modifications they’re doing to the output of your pages). It’s called mod_pagespeed and the code page (where you can get it) explains what it does to optimize all web pages served on Apache. They provide a list of the filters which the mod implements to actually rewrite the output of your pages in a way that results in less traffic and better browser rendering. How? Well, take a look at this example:

The “CSS Combine” filter finds all CSStags. If there was more than one in a flush window, it removes each of those links and replaces them with a single to the merged document, which it places wherever the first CSSoriginally was.

In other words, the module will take all your CSS files, combine them into one big CSS file, and alter your link to point to the new consolidated file. This is something that can really ease the workload on someone who has dabbled in optimizing page speed. Now you don’t have to have separate development and production copies of your CSS files. This will smush them together for you.

It can likewise minify your javascript for you! No more running your code through JSLint. Your web server will handle that.

Simple. Awesome. I have yet to test it out, but this is a great idea. Manually doing these tasks is a waste of time. This could well become a must-have for any self respecting web dev.

Apple Rejects Flash

Posted by
admin
.

In an ironic twist, Apple CEO Steve Jobs has written a post about Apple’s decision not to support flash on their mobile devices like iphones and ipads. Jobs paints a picture of flash as being outdated, restrictive, and designed for the “PC era”. Many of his comments are a direct response to an article by Adobe about the future of Flash technology, which is their response to what others have been saying. Adobe says they’re open, secure, widely used, and supportive of innovation. Apple (and others) say they’re limiting, closed, insecure, and quickly being outdated by html5 and javascript advancements.

The irony of the situation is that Apple and Adobe have been like brothers in the software industry for years. Adobe’s products have always come hand-in-hand with Apple’s products. Things like native support for postscript and acrobat, and a mutual target market group of designers and artists have meant that these two companies thrived together.

Where do I stand?

Like many web developers, I agree with Apple’s decision and the bulk of what Jobs is saying in his letter. I don’t take the extreme position that some developers take when they make blanket statements like “no website should ever be made in flash” (trust me, I’ve heard this a few times). Flash is graphically rich, has sound, and can create extremely flexible and responsive web applications. Creating a professional website for a musician without flash is currently impractical unless you want to forget about playing music on the site for viewers without sufficient html5 support. It would be great if everyone used Firefox, but in practical terms, there are still 20% of people out there using ie6! Clearly we have quite a while before we can replace flash with something new.

But the fact of the matter is that flash is acting as a crutch until a better system can be adopted to do most of these things. Primarily video and audio. Adobe should accept the fact that a software level rendering environment for video is not the future, and that web developers are going to jump on the ability to put sound onto websites without having to publish it from CS4 (or CS5, or any proprietary development environment). Obviously we want the freedom to throw it up with a few lines of javascript, without the time consuming overhead. The reason we don’t is because we can’t, not because Flash is ideal.

Adobe cites some obviously biased figures about how 85% of the top 100 websites use flash. Having an optional flash component to throw some spice onto a website that could easily be replaced by html5 when it’s practical to do so is not looking ahead. Most of the flash I come across is already annoying and unnecessary, unviewable at work (where nobody gets flash to prevent them from watching youtube all day), blocked by noscript or adblocker, and could be replaced by a good jquery coder.

The future is that Flash will become relegated to what it’s actually best for: non-mobile, browser based applications like those goofy games where you hit a penguin with a club to see how far it will go. If Adobe is quick on the ball and manages to code it extremely well, flash might get well supported on mobile devices, but they’re taking too long to provide touch support, and they may never fully convince developers that it’s not a security risk to support it on that kind of platform.

Canonical Link Element: one link to rule them all

Posted by
admin
.

According to SEO guru Matt Cutts (he works at google and is quite renowned for helping us web devs out) a promising new link element that is now being supported by major SEO companies (all we really care about these days is google, isn’t it? I’m sure that’ll change someday. Maybe.) called the canonical link.

This link tag is used to specify how search engines (not to people, although who knows how a user agent might use it in the future) should treat those weird, argument filled URLs that get generated by scripts (like phpbb or this blog) that end in something like mydomain.com/forum/viewtopic.php?t=343&f=2 or maybe a session ID at the end of the link like ?SID=3429vhr32if298fg.

For a long time now we’ve been forced to modify our software in all kinds of complicated ways to stop search engines from treating these pages as separate pages when they are often the same page accessed with a different argument.

No longer! Well, not so much anyway. We’ll still need to modify software if we want search friendly URLs. And, actually, google seems to be pretty smart when it comes to detecting duplicate content as a result of variables appended to URLs. Still, I would choose this option over heavy modifications… Actually the more I think about it, the more I realize this is far from a magic bullet… Oh well.

By specifying a canonical link element to a page, crawlers will ignore all that junk at the end of the URL and only index the one, canonical link. It’s also called “normalizing” your URLs. How to do it? Well where you actually implement the code on your software may vary (doing it for phpbb3 culd be tricky if you want all the pages to still get indexed) but the code itself is simple as pie.

<link rel="canonical" href="http://example.com/page.html"/>

Done. Now they know the page to index is page.html and not page.html?doodle=234975ai398r&biddle=34y

Sweet. Oh, and you can use it to deal with that pesky www subdomain issue. Don’t want google treating www.yourdomain.com and yourdomain.com as different URLs? Just normalize it as above. Woohoo!

Incidentally, the google webmaster tools also has a relatively new option in there to specify a preferred subdomain. I would think these two tools go hand in hand quite nicely.

Just go read his blog entry on it if you need more info. It’s got a cute slideshow that breaks it down for ya.

Canonical Link Element: one link to rule them all

Posted by
admin
.

According to SEO guru Matt Cutts (he works at google and is quite renowned for helping us web devs out) a promising new link element that is now being supported by major SEO companies (all we really care about these days is google, isn’t it? I’m sure that’ll change someday. Maybe.) called the canonical link.

This link tag is used to specify how search engines (not to people, although who knows how a user agent might use it in the future) should treat those weird, argument filled URLs that get generated by scripts (like phpbb or this blog) that end in something like mydomain.com/forum/viewtopic.php?t=343&f=2 or maybe a session ID at the end of the link like ?SID=3429vhr32if298fg.

For a long time now we’ve been forced to modify our software in all kinds of complicated ways to stop search engines from treating these pages as separate pages when they are often the same page accessed with a different argument.

No longer! Well, not so much anyway. We’ll still need to modify software if we want search friendly URLs. And, actually, google seems to be pretty smart when it comes to detecting duplicate content as a result of variables appended to URLs. Still, I would choose this option over heavy modifications… Actually the more I think about it, the more I realize this is far from a magic bullet… Oh well.

By specifying a canonical link element to a page, crawlers will ignore all that junk at the end of the URL and only index the one, canonical link. It’s also called “normalizing” your URLs. How to do it? Well where you actually implement the code on your software may vary (doing it for phpbb3 culd be tricky if you want all the pages to still get indexed) but the code itself is simple as pie.

<link rel="canonical" href="http://example.com/page.html"/>

Done. Now they know the page to index is page.html and not page.html?doodle=234975ai398r&biddle=34y

Sweet. Oh, and you can use it to deal with that pesky www subdomain issue. Don’t want google treating www.yourdomain.com and yourdomain.com as different URLs? Just normalize it as above. Woohoo!

Incidentally, the google webmaster tools also has a relatively new option in there to specify a preferred subdomain. I would think these two tools go hand in hand quite nicely.

Just go read his blog entry on it if you need more info. It’s got a cute slideshow that breaks it down for ya.

Google and meta Keywords

Posted by
admin
.

Let it be settled once and for all. Google does not use the meta keywords tag when ranking page results.

Anyone involved in web development has had to answer questions now and then regarding what can be done to achieve good search engine ranking, and anyone who has seriously looked into the issue knows that Google keeps many of their methods secret, leaving us, the users, to figure it out by guessing and twisting their virtual arms to get answers. Many of the essential methods have already come to light as Google has voluntarily given advice they feel we ought to know. Incoming and outgoing links, relevant content, page titles, and well structured pages are the primary methods. But what about meta tags?

Well, Google has finally laid the keywords meta tag to rest by openly stating that they don’t use it. This should not come as a big surprise to anyone following SEO techniques. A meta tag filled up with spam words goes against everything Google’s philosophy stands for. It is far too easy to fill up this tag with whatever information you want and it was (and still is) the primary target of old-fashioned keyword stuffing methods. Any time something on a website is invisible to the visitors, it is probably either considered black hat or ignored as irrelevant by Google. In the same article, Google explains that it doesn’t really use the description meta tag for ranking either, only for page listings (something users will see if they visit your site from Google).

It is still up in the air if other search engines will use keywords. Many probably do, so it is worth adding a few for the sake of completeness, but the next time a sell prescribed SEO ‘expert’ tells you that keywords are important, you’ll know better. Nothing beats incoming links and page content, and nothing ever will.