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
    An Interview with Eric Meyer

    Your early CSS books were instrumental in pushing my love for front end technologies. What was it about CSS that you fell in love with and drove you to write about it? At first blush, it was the simplicity of it as compared to the table-and-spacer...

  • By
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

Incredible Demos

  • By
    MooTools History Plugin

    One of the reasons I love AJAX technology so much is because it allows us to avoid unnecessary page loads.  Why download the header, footer, and other static data multiple times if that specific data never changes?  It's a waste of time, processing, and bandwidth.  Unfortunately...

  • By
    MooTools Overlay Plugin

    Overlays have become a big part of modern websites; we can probably attribute that to the numerous lightboxes that use them. I've found a ton of overlay code snippets out there but none of them satisfy my taste in code. Many of them are...

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!