jQuery Wordpress

Customizing checkboxes with jQuery

When you develop a wordpress theme, the idea is to make it usable by other people. Even though I’m developing this one for my one purpose, I have to keep that in mind. For instance, listing categories with images in the header might not suit everyone’s needs.

That’s the reason why wordpress themes usually allow you to select number of options in a dedicated admin section. I want to show you how you can easily customize your checkboxes using jQuery, so that they don’t look like the default ones you see everywhere.

checkbox_normLet’s say we have a simple liste of options with checkboxes, like the one in the example.

This could be the HTML structure  used to do so :

So, what are we to do with jQuery ?

Well, first thing’s first, we need to hide those checkboxes, and I really mean hide, and not remove. Then, instead of the checkbox, we want an image that will reflect the state of the checkbox : checked or not. The image – or icon – could be added as a DOM element to the label of the checkbox, or just inserted as CSS background. We’ll use the later as it only requires changing a class name. And finally, we need to deal with the click action on the labels, so that the icon is changed reflecting the state of the checkbox.

Ok then, let’s define our CSS classes first, if the icons are 16px wide, it could be something like this :

And here’s for the jQuery :

Quite simple, isn’t it ?

checkbox_styleJust so that you know why the checkboxes must be hidden and not removed : when the form is submitted, their state is taken into account ! Even though they’re hidden, they change from checked / unchecked when you click on the label.

And here’s what it looks like : pretty cool for very little effort !

You’d probably find loads of customized form elements on the web, but if you want to make your own, this is the way to go !