Monday, 4 January 2010

Making a Image Appear Blurred and Sharpen When Mouse Is Over Using jQuery



A simple way to blur any image using jQuery.
The code does it by creating 4 more instances of the image and by positioning it to the left, right, top and below and setting the opacity so they are all see through.
The image will NOT be downloaded more than once and therefore it will not need as much bandwidth compared with if you created two images - ie one blurred and one sharp.

For more of a blur, increase the containing DIVs padding. It is also important to set the width and height the same size as the image otherwise the created images will be placed all over the place



The CSS


.blur {
 padding:2.5px; /* To change the amount of blur, change this value */
 width:385px; /* Width of image */
 height:540px; /* Height of image */
 margin:0;
 position:relative;
}
.blur img {
 border:none;
 opacity:0.40;
 filter:alpha(opacity=40);
}

The JavaScript


$(document).ready(function () {
 $(".blur img").each(function() {
  var t=$(this).attr("src");
  $(this).parent().append('<img src="'+t+'" style="left: 0px; position: absolute; top: 0px;" />');
  $(this).parent().append('<img src="'+t+'" style="position: absolute; right: 0px; top: 0px;" />');
  $(this).parent().append('<img src="'+t+'" style="bottom: 0px; left: 0px; position: absolute;" />');
  $(this).parent().append('<img src="'+t+'" style="bottom: 0px; position: absolute; right: 0px;" />');
 });
 $(".blur").hover(function() {
  $('img:eq(0)',$(this)).stop()
   .fadeTo("fast",1.00);        
  $('img:gt(0)',$(this)).stop()
   .fadeTo("slow",0.00);
 },function() {
  $('img:eq(0)',$(this)).stop()
   .fadeTo("slow",0.40);
  $('img:gt(0)',$(this)).stop()
   .fadeTo("slow",0.40);
 });
});

The HTML


<div class="blur">
<img src="/eiffeltower.jpg" />
</div>

...or...

<div class="blur" style="padding: 5px;">
<img src="/eiffeltower.jpg" />
</div>

0 comments:

DoFollow Blog

Post a Comment

Why not leave a comment... What harm can it do?