JavaScript CSS Helpers

By  on  

I spend a good amount of time looking at JavaScript framework source code. Regardless of which frameworks you have allegiance to, you can learn an awful lot by looking under the hood of widely used code collections. One of many handy snippets can be found within the MooTools source code: functions to camelize and hyphenate strings so that your own min framework can accept either form of CSS setter or getter. Here are the functions in all of their glory.

The JavaScript

As you could probably guess, this task is best accomplished with regular expressions:

function camelize(str) {
	return (str + "").replace(/-\D/g, function(match) {
		return match.charAt(1).toUpperCase();
	});
}
camelize("border-bottom-color"); // "borderBottomColor"


function hyphenate(str) {
	return (str + "").replace(/[A-Z]/g, function(match) {
		return "-" + match.toLowerCase();
	});
}
hyphenate("borderBottomColor"); // "border-bottom-color"

A couple of really handy JavaScript String to corresponding String format functions. Instead of expecting strings in only one format, your mini library can now accept both!

Recent Features

Incredible Demos

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    Add Site Screenshots for External Links Using MooTools Tooltips

    Before you send your user to an unknown external website, why not provide them a screenshot of the site via a tooltip so they may preview the upcoming page? Here's how you can do just that using MooTools. The MooTools JavaScript The first step is to grab...

Discussion

  1. dvdrtrgn

    That code is nice and purdy.
    I do loves me some concision.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!