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
    Chris Coyier’s Favorite CodePen Demos

    David asked me if I'd be up for a guest post picking out some of my favorite Pens from CodePen. A daunting task! There are so many! I managed to pick a few though that have blown me away over the past few months. If you...

  • By
    7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos

  • By
    MooTools Zebra Tables Plugin

    Tabular data can oftentimes be boring, but it doesn't need to look that way! With a small MooTools class, I can make tabular data extremely easy to read by implementing "zebra" tables -- tables with alternating row background colors. The CSS The above CSS is extremely basic.

  • By
    MooTools TwitterGitter Plugin

    Everyone loves Twitter. Everyone loves MooTools. That's why everyone should love TwitterGitter, a MooTools plugin that retrieves a user's recent tweets and allows the user to format them however the user would like. TwitterGitter allows the user to choose the number of...

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!