How to extend jQuery.css from the plugin

I wrote a very simple plugin that allows me to use the 0xffccaa format for css colors instead of '#ffccaa' (mainly to avoid writing quotes), but also makes it easy to change colors by simply adding to it as an integer).

I implement as $().xcss({}) , but prefer to just use $().css({}) .

How can I extend the functionality of the $.fn.css function, and are there any pitfalls that I should pay attention to?

Also, I think I 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(/.*([af\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>') 
+8
jquery css jquery-animate plugins
source share
2 answers

This works 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(/.*([af\d]{6})$/, '#$1') }) return _css.apply(this, [opts]); // call original method } })(jQuery) 
+5
source share

https://github.com/aheckmann/jquery.hook/blob/master/jquery.hook.js

Based on this code, to create hooks for arbitrary functions, you can simply override $ .fn.css with a method that does what you want before calling the original function.

+2
source share

All Articles