I have written a very simple plugin that allows me to use 0xffccaa
format for css colours instead of '#ffccaa'
(mostly to avoid writing quotes - but also to allow easy modification of colours by simply adding to it as an integer).
I am implementing as $().xcss({})
, but would prefer to just use $().css({})
.
How can I extend the functionality of the $.fn.css
function, and are there any pitfalls I need to watch out for?
Also, I guess I will want to do the same for $.animate
.
Fiddle: http://jsfiddle.net/hB4R8/
// pugin wrapper
(function($){ $.fn.xcss = function(opts){
// loop through css color properties
$.each(['background', 'backgroundColor','background-color', 'color', 'borderColor','border-color'],function(i,v){
// if set as number (will be integer - not hex at this point)
// convert the value to `#ffccaa` format (adds padding if needed)
if(typeof opts[v] === 'number')
opts[v] = ('00000'+opts[v].toString(16)).replace(/.*([a-f\d]{6})$/,'#$1')
})
// run css funciton with modified options
this.css(opts)
// allow chaining
return this
} })(jQuery)
// test the plugin
$('body').xcss({
'background-color': 0xffccFF,
color: 0xccffcc,
border: '3px solid red',
borderColor:0x0ccaa,
padding:50
}).html('<h1>This should be a funny color</h1>')
This seems to work for me: http://jsfiddle.net/frfdj/
(function($) {
var _css = $.fn.css; // store method being overridden
$.fn.css = function(opts) {
$.each(['background', 'backgroundColor', 'background-color', 'color', 'borderColor', 'border-color'], function(i, v) {
if (typeof opts[v] === 'number') opts[v] = ('00000' + opts[v].toString(16)).replace(/.*([a-f\d]{6})$/, '#$1')
})
return _css.apply(this, [opts]); // call original method
}
})(jQuery)
https://github.com/aheckmann/jquery.hook/blob/master/jquery.hook.js
Based on this code for creating hooks for arbitrary functions, you can just override $.fn.css with a method that does what you want before calling the original function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With