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
    CSS content and attr

    CSS is becoming more and more powerful but in the sense that it allows us to do the little things easily.  There have been larger features added like transitions, animations, and transforms, but one feature that goes under the radar is generated content.  You saw a...

  • By
    Animated AJAX Record Deletion Using MooTools

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with MooTools JavaScript. The PHP - Content & Header The following snippet goes at the...

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!