I've played with jQuery for some time now but have never written my own plugin.
A question was asked: "can I blur an image using jQuery?" and I thought this to be a decent candidate to play with.
Here's my code so far:
(function ($) {
$.fn.blurStuff = function (options) {
var defaults = {blurRadius:2, deblurOnHover:false};
var settings = $.extend(defaults, options);
$(this).wrap('<div data-blurimage />');
var blurContainers = $(this).closest('[data-blurimage]');
blurContainers.each(function () {
var img = $(this).children();
$(this).css({
'width': img.width(),
'height': img.height(),
'overflow': 'hidden',
'position': 'relative'
});
var clone = img.clone();
clone.css({
'opacity': 0.2,
'position': 'absolute'
});
$(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': +settings.blurRadius}));
$(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': +settings.blurRadius}));
$(this).append(clone.clone().css({'left': +settings.blurRadius, 'top': -settings.blurRadius}));
$(this).append(clone.clone().css({'left': -settings.blurRadius, 'top': -settings.blurRadius}));
});
if (settings.deblurOnHover == true) {
blurContainers.hover(function () {
$(this).children('img:gt(0)').toggle();
});
}
return blurContainers;
};
})(jQuery);
In action: http://jsfiddle.net/gvee/xvvWj/
Example usage:
$('img').blurStuff({deblurOnHover: true, blurRadius: 2});
My working logic is to wrap the selector in a parent container and then append 4 translucent clones to this, where each clone is positioned slightly off centre.
This works pretty well so far and I'm pleased with my progress but I can conceive a couple of potential bugs that I wanted some opinions on!
- Is my approach reasonable? I realise that I'm appending an extra 4 elements to the DOM on each call which is not ideal (I could get away with using just two, laterally or diagonally, but I think 4 produces a better effect)...
- What to do if a user passes a
fixed
position element? This will break existing flow. - Should I bother validating/sanity checking the parameter values? If so, how should I approach this? Previously I had a parameter called
blurOpacity
but I removed this because I realised that the wrong values (e.g.1
) effectively "breaks" things.