To better learn jquery I decided to write a plugin that creates a gallery collage effect like google+. Here’s an example.
I want to trigger it again on resizing the html element that contains the images. Part of the problem I’m having is that I need to store the original image size in order to recalculate the image sizes to make them fit.
I don’t know where to store and how to retrieve those original image sizes. Full plugin is linked above, but I’ll put a summary here.
;(function( $ ) {
$.fn.collagePlus = function( options ) {
var settings = $.extend(
//...
'images' : $('img', $(this))
//...
);
return this.each(function() {
settings.images.each(function(index){
//...
/*
* get the current image size
*/
var w = (typeof $(this).data().width != 'undefined') ? $(this).data().width : $(this).width();
var h = (typeof $(this).data().height != 'undefined') ? $(this).data().height : $(this).height();
/*
* store the original size for resize events
*/
$(this).attr( "data-width" , w );
$(this).attr( "data-height" , h );
//... Do some other stuff
}
);
});
}
})( jQuery );
You’re using
.data()wrong. When you pass 1 parameter to the.datafunction, it returns the value for the given key. When you pass 2 parameters,.datawill set the value for that key.This block:
Should be:
And of course, to retrieve the data later:
Fiddle Demo
You can also store an object in the
.datapassing a map of properties:Now
widthandheightare properties of the object stored in the.data('size'), which can retrieved with:Fiddle
For the sake of simplicity, I’d primarily go with the first option. However the second one looks tidier. Choose whichever you find more readable and maintainable.