Skip to content

Instantly share code, notes, and snippets.

@kpnemo
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save kpnemo/f8f00a8063af0dda6ad9 to your computer and use it in GitHub Desktop.

Select an option

Save kpnemo/f8f00a8063af0dda6ad9 to your computer and use it in GitHub Desktop.
jQuery image enlarge on click to its original size
/**
* Image enlarge on click
*/
(function( $ ){
var _settings = {
cursor: 'crosshair',
animationTime: 300,
watchResize: true
}
var _toggleImage = function(img, ev){
if(img.hasClass('_jquery-img-enlarged')) return;
img.addClass('_jquery-img-enlarged');
var $img = img.clone().addClass('_jquery-img-enlarged-copy').appendTo('body');
$img.css({
width: img[0].clientWidth,
height: img[0].clientHeight,
position: 'absolute',
top: img.offset().top,
left: img.offset().left
}).animate({
width: img[0].naturalWidth,
height: img[0].naturalHeight
}, _settings.animationTime).one('click', function(ev){
ev.preventDefault();
$img.animate({
height: img[0].clientHeight,
width: img[0].clientWidth
}, _settings.animationTime, function(){
$img.remove();
img.removeClass('_jquery-img-enlarged');
});
})
}
$.fn.imgEnlarge = function( options ) {
var that = this;
if(options) $.extend(_settings, options);
var _bindImages = function(){
return that.each(function(index, img){
if(img.clientWidth < img.naturalWidth){
$(img).css({cursor: _settings.cursor});
$(img).on('click', function(ev){
ev.preventDefault();
_toggleImage($(this), ev);
});
} else {
$(img).css({cursor: 'default'});
$(img).off('click');
}
});
};
if(_settings.watchResize){
$(window).on('resize', function(){
$('._jquery-img-enlarged-copy').remove();
$('._jquery-img-enlarged').removeClass('_jquery-img-enlarged');
_bindImages();
});
}
return _bindImages();
};
})( window.jQuery || window.Zepto );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment