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

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Incredible Demos

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!