I set out to make a simple dynamic resize method for images. Obviously, it's better to serve images that are pre-sized to avoid unnecessary server loads. But it was fun to make for a novice/beginner jQuery project and not really meant for a production project. For many of you, I'm sure it'll be rudimentary at best, but that's why I'm posting it here, to get some advice on ways to improve it.
The goal,
- Add wrappers dynamically (using the wrapInner method for content structure inside the collection of elements with class topic), add wrapper around images to constrain the content image sizes.
- dynamic width & height attributes on images - onLoad & onResize
- Dynamic query string on img.src (URL adds ?width=###&height=###) onLoad & resize (for demo purposes I'm using "placehold.it/###x###") this is only needed for content images in the DOM.
- Real width & height of image set to parent (figure) as max-width/height onLoad
- Debounce/throttle resize events to avoid excess events begin fired. (used a method displayed on css-tricks.com and can be found here)
The CSS and HTML is more to make the demo look nice but if you have some input for that as well, by all means. Like I said, I'm certainly not a jQuery developer, though I'm trying to learn as quickly as possible to augment my skill set. So if you have any advice or input on areas that can improve, I'd greatly appreciate it.
Fiddle: DEMO
$(function() {
// demo fun
$('.topic').each(function() {
var $this = $(this),
ifMedia = $this.find('.media');
$this.wrapInner('<section class="content"/>');
if (ifMedia.length) {
$this.addClass('media-support');
}
if ($this.hasClass('media-support')) {
$('.media-support:odd').addClass('inverse');
}
});
});
var sizeTimer;
$(window).on('load', function() {
var img = new Image();
$('img').each(function() {
var $this = $(this),
image = new Image(),
_imgWidth = $(this).width(),
_imgHeight = $(this).height(),
_naturalWidth = this.naturalWidth,
_naturalHeight = this.naturalHeight;
image.src = $(this).attr("src");
$this.attr({
'width': +_imgWidth,
'height': +_imgHeight,
'src': '//placehold.it/' + _imgWidth + 'x' + _imgHeight
}).wrap('<figure class="image" />').closest('.image').css({
'max-width': _naturalWidth,
'max-height': _naturalHeight
});
});
}).on('resize', function() {
clearTimeout(sizeTimer);
sizeTimer = setTimeout(function() {
$('img').each(function() {
var $this = $(this),
_imgWidth = $(this).width(),
_imgHeight = $(this).height();
$this.attr({
'width': _imgWidth,
'height': _imgHeight,
'src': '//placehold.it/' + _imgWidth + 'x' + _imgHeight
});
});
}, 250);
});