Playing with CSS hooks

So, I wanted to give the new CSS hooks in jQuery a try. Unfortunately, the usually well documented jQuery has this as the total documentation on the hooks:

As of version 1.4.3, jQuery’s CSS module was rewritten to provide a set of “hooks” for the .css() method. This advanced feature, $.cssHooks, allows for fine-grained control over the way jQuery handles certain style properties and enables the creation of custom, browser-normalized properties. The $.cssHooks object also extends the set of properties available to the .animate() method.

Which isn’t much to go on. So, I broke out the old source code to see whats up. Basically, you can hook into a CSS property and create setters and getters for it. I started by making a simple hook that allows you to use show and hide on the display property, and have it call show() and hide(). The code is pretty simple:


jQuery.cssHooks.display = {
set: function(elem, value) {
if (typeof (value) === 'string') {
if (value === 'hide') {
$(elem).hide();
} else if (value === 'show') {
$(elem).show();
} else {
elem.style['display'] = value;
}
} else {
if (value.hide) {
$(elem).hide(value.hide);
} else if (value.show) {
$(elem).show(value.show);
} else {
elem.style['display'] = value;
}
}
}
};

This simply checks if you are passing in a string or an object, and then calls show/hide with the supplied value (in the case of an object.) If you are not using show/hide it runs node.style[‘display’] = value; which is what normally happens when you call .css.

I made an example for it here:

I’m a thing!




The code here is pretty simple too:


$('#hookButton').click(function(e) {
var $this = $(this);
if($this.text() === 'Hide') {
$('#cssHookTest').css('display', 'hide');
$this.text('Show');
} else {
$('#cssHookTest').css('display', 'show');
$this.text('Hide');
}
});

$('#hookButton2').click(function(e) {
var $this = $(this);
if($this.text() === 'Hide Slow') {
$('#cssHookTest').css('display', {'hide': 'slow'});
$this.text('Show Slow');
} else {
$('#cssHookTest').css('display', {'show': 'slow'});
$this.text('Hide Slow');
}
});

$('#hookButton3').click(function(e) {
var $this = $(this);
if($this.text() === 'Hide REALLY Slow') {
$('#cssHookTest').css('display', {'hide': 1400});
$this.text('Show REALLY Slow');
} else {
$('#cssHookTest').css('display', {'show': 1400});
$this.text('Hide REALLY Slow');
}
});

$('#hookButton4').click(function(e) {
var $this = $(this);
if($this.text() === 'Hide Normal') {
$('#cssHookTest').css('display', 'none');
$this.text('Show Slow');
} else {
$('#cssHookTest').css('display', 'block');
$this.text('Hide Normal');
}
});

So, that’s about it, the CSS hooks, although called an advanced feature are really not that hard to use. So, give ’em a try.

Leave a Reply

Your email address will not be published. Required fields are marked *