So I’m writing a jQuery plugin to apply retina graphics. I need to select an element (if it has a background image or a source image) and then every element inside of it (if it has a background image or a source image).
Here’s my plugin:
//RetinizeJS
(function($){
$.fn.retinize = function(){
$(this).filter(function(){
if (this.currentStyle)
return this.currentStyle['backgroundImage'] !== 'none';
else if (window.getComputedStyle)
return document.defaultView.getComputedStyle(this,null)
.getPropertyValue('background-image') !== 'none';
}).addClass('bg_found');
};
})(jQuery);
$('body').retinize();
That needs to return the body element if it has a background image, and all the elements within if they are <img src="" /> or if they have a CSS background-image property.
How can I achieve this?
UPDATE 9:13 PM:
This doesn’t add the class HAS_IMAGE to anything, and it still doesn’t select the <img> elements if i remove || ($this.css('backgroundImage') !== 'none');.
//RetinizeJS
(function($){
$.fn.retinize = function(){
$this = $(this);
$this.find('*').andSelf().filter(function(){
return $this.is('img') || ($this.css('backgroundImage') !== 'none');
}).addClass('HAS_IMAGE');
};
})(jQuery);
$('body').retinize()
You can check if an element has a certain CSS rule value by using
.css(). I’m thinking (i.e. not tested) that by checking.css('backgroundImage'), you should be able to check if an element has a background image, whether or not it was set using CSSbackgroundor CSSbackground-image.You can use that knowledge to set up a filter function like so:
You’ll just have to work on how that cascades into the descendants with your plugin.
However, if you’re rigidly having to check from
<body>, then extending$.fnsounds like the wrong way to go.$.fnextensions are meant for functions that act on a jQuery object, like$('body').retinize()or$('div img').retinize().You’d probably want to make that a utility function instead by extending directly into
$, so you can call it via$.retinize()or something.