Resize Images in a Post with jQuery, and turn it into a plugin

If you own a blog, chances are you post pictures in your posts once in a while. Likewise, you have probably encountered the problem of resizing the images so that they fit in the post. Today’s tutorial will be in two steps:

  1. We will write a jquery function to handle the image resizing
  2. We will convert the resulting code into a plugin

We will use two images, test1.jpg and test2.jpg:

Part 1:

Now that we have these, we can move on to the html:

<div id="post">
		
	<img src="testpic.jpg" class="resized">

	<img src="test.jpg">

</div>

Since the result looks insufferably plain, we’ll add some text to fill up the space.

<div id="post">
Nec porttitor integer, eros facilisis, tristique nisi cursus turpis sociis placerat nunc porttitor, vut tempor dictumst rhoncus cursus sed dolor ridiculus, sed scelerisque magna, sed, penatibus turpis? Vel turpis tristique? Pulvinar integer? Ac dignissim rhoncus nascetur eu et tristique, nec nisi amet! Duis sit pulvinar magna a vel? Augue in pellentesque sagittis facilisis eros! Elementum, augue, lundium, urna nunc pulvinar, aliquam facilisis? Sociis! A cras dictumst! Ac pulvinar lundium pellentesque, dolor tortor, turpis ridiculus nec montes scelerisque cum. Est tincidunt, lundium nunc eu nec. Habitasse! Auctor tincidunt turpis, amet nec! Platea mus sociis, a est rhoncus, magna ac! Porttitor scelerisque? Dictumst placerat duis auctor arcu. Ultrices? Dignissim nisi, a purus elit nec sed odio, magna auctor dolor magna tortor lundium.
			
<img src="test1.jpg">

Nisi sed porttitor, mid aliquet, a enim nunc scelerisque nunc elit? Ultricies adipiscing dolor, porta integer. Adipiscing nec dolor adipiscing sit, mid platea in magna porttitor! Ac placerat porta vel proin tempor tristique! Aenean pulvinar tincidunt aliquet hac in duis duis sociis turpis! Velit? Scelerisque amet enim, phasellus natoque auctor augue nascetur ridiculus elit sociis ac urna, ultrices nascetur. Lundium nunc, cum in elit, turpis auctor! Vel in amet. Turpis massa tincidunt non vel a? Placerat nisi amet odio a sit pulvinar, arcu in lorem pulvinar? Elementum, aliquet non placerat purus! Rhoncus amet purus ut, dictumst turpis integer duis sit nisi, turpis ac, arcu. Lacus et mus vut adipiscing, porttitor parturient dictumst facilisis, parturient montes adipiscing aliquet pulvinar dictumst.


<img src="test2.jpg">

Facilisis. Nunc a magnis montes quis, odio cum mus dignissim eu, rhoncus adipiscing odio elementum sit turpis enim urna! Nisi in sed dictumst sit et. Sociis? Odio ac mus, augue nec vut etiam in, pulvinar. Diam cursus turpis ac. Tristique nisi. Sit velit aenean, sociis montes elementum aenean in arcu ultricies nec non enim nec augue adipiscing aliquam a odio, amet tempor dictumst! Nisi, turpis. Placerat cursus urna lorem purus dolor in integer massa dolor vel proin, pulvinar et, aenean proin dolor? Scelerisque. Lundium proin turpis elit? Dignissim hac. Turpis lorem augue, parturient augue habitasse amet a nisi egestas tortor rhoncus et porta, odio ut et, nascetur integer et et nec mus sit, risus habitasse massa, rhoncus augue aliquam.
		</div>

Now that we have the basic html markup, let’s make the styling a little more post-like.


#post {
font-family: 'Arial';
color: #3a3a3a;
font-size: 15px;
line-height: 25px;
width: 640px;
padding-left: 10px;
padding-right: 10px;
margin: 0 auto;
background: #eeeeee;
}

As you can see, the second image is wider than the post.

Now, we’ll write the code that will fix this.

First off, we will create a function that will handle all our code. We will also give this function one parameter, “el”. “El” will be the images that we will resize. In this case, ‘#post img’.
[js]
function resizeImages(el){

}
[/js]

Now, we will use jQuery’s each() function to iterate over each image.

[js]
function resizeImages(el){

$(el).each(function(){

});

}
[/js]

Next, we have to figure out the max width that the pictures can be.

[js]
function resizeImages(el){

$(el).each(function(){

var maxWidth = $(this).parent().width();

});
}
[/js]

jQuery’s .parent() returns the current element’s immediate parent. So, the maxWidth variable is set to the post’s width.

Next, we have to find out the width and height of the images.

[js]
function resizeImages(el){

$(el).each(function(){

var maxWidth = $(this).parent().width();

var imgWidth = $(this).width();
var imgHeight = $(this).height();

});

}
[/js]

The reason we are using .width() and .height() instead of .css(“width”) and .css(“height”) is because when we use the .css() function, we also get the units tacked on. That won’t work out when we start to do the math.

Now, we calculate the new width and height of our current image.
[js]
function resizeImages(el){

$(el).each(function(){

var maxWidth = $(this).parent().width();

var imgWidth = $(this).width();
var imgHeight = $(this).height();

var newWidth = maxWidth;

var ratio = imgWidth/maxWidth;

var newHeight = imgHeight/ratio;

});

}
[/js]

Let me explain. The new width will be the max width. Fairly self-explanatory. Now, in order to calculate the new height, we have to figure out the ratio between the old width and height. Hence, the ratio variable. We then set the new height by dividing the original height by the ratio.

Next is the easiest part. We give the current image its new width and height.
[js]
function resizeImages(el){

$(el).each(function(){

var maxWidth = $(this).parent().width();

var imgWidth = $(this).width();
var imgHeight = $(this).height();

var newWidth = maxWidth;

var ratio = imgWidth/maxWidth;

var newHeight = imgHeight/ratio;

$(this).css({
height: newHeight,
width: newWidth,
});

});

}
[/js]

And last, but certainly not least, we initialise the function:
[js]
$(document).ready(function(){

resizeImages(‘#post img’);

});
[/js]

Ta-da! We now have a working function that resizes the images in a post. Read on to find out how to turn this into a plugin.

Part 2:

Now, we’ll turn this into a plugin called resizeimg. Very original, yes. First, we’ll start off with a simple plugin starter template.
[js]
(function($){
$.fn.extend({
//plugin name – resizeimg
resizeimg: function(options) {

//Settings list and the default values
var defaults = {
maxWidth: 0,
};

var options = $.extend(defaults, options);

return this.each(function() {
var o = options;

//Assign current element to variable, in this case is UL element
var obj = $(this);

//Plugin code goes here

});
}
});
})(jQuery);
[/js]

This is a generic plugin starter template. You can use this for whatever you want. Credits to the guys over at Queness for this one.

Now, we just carefully copy-paste our function into this. We don’t actually have to copy-paste the function wrapper, since the plugin already provides us with a nice function to put our code in. We also don’t need our .each function either, since once again, the plugin already does that.
[js]
(function($){
$.fn.extend({
//plugin name – resizeimg
resizeimg: function(options) {

//Settings list and the default values
var defaults = {
maxWidth: 0,
};

var options = $.extend(defaults, options);

//The each function is already here
return this.each(function() {
var o = options;

//Assign current element to variable, in this case is UL element
var obj = $(this);

//Plugin code goes here

var maxWidth = $(this).parent().width();

var imgWidth = $(this).width();
var imgHeight = $(this).height();

var newWidth = maxWidth;

var ratio = imgWidth/maxWidth;

var newHeight = imgHeight/ratio;

$(this).css({
height: newHeight,
width: newWidth,
});

});
}
});
})(jQuery);
[/js]

Great! Now we can modify the existing code a little. However, before we do that, take a look at settings list. We have one paramater, maxWidth. You will see how to use this later.

Now, notice we have an “obj” variable. We will use it instead of wrapping everything in $(this). In the long term, using a small variable like “obj” helps.

[js]
var o = options;

//Assign current element to variable, in this case is UL element
var obj = $(this);

//Plugin code goes here

var maxWidth = obj.parent().width();

var imgWidth = obj.width();
var imgHeight = obj.height();

var newWidth = maxWidth;

var ratio = imgWidth/maxWidth;

var newHeight = imgHeight/ratio;

obj.css({
height: newHeight,
width: newWidth,
});
[/js]

Great, but now we have to make the maxWidth variable use the parameter, and if a parameter isn’t specified, or is 0, use our good old .parent() function.

[js]
//Plugin code goes here

var maxWidth = o.maxWidth;
//By default, maxWidth will be 0
if(maxWidth == 0){
var maxWidth = obj.parent().width();
}
//if maxWidth is set,
else {
var maxWidth = o.maxWidth;
}
[/js]

Once we’ve done that, the plugin is finished! Here’s the final code for your copy-pasting pleasure.
[js]
(function($){
$.fn.extend({
//plugin name – resizeimg
resizeimg: function(options) {

//Settings list and the default values
var defaults = {
maxWidth: 0,
};

var options = $.extend(defaults, options);

return this.each(function() {
var o = options;

//Assign current element to variable, in this case is UL element
var obj = $(this);

//Plugin code goes here

var maxWidth = o.maxWidth;

if(maxWidth == 0){
var maxWidth = obj.parent().width();
}
else {
var maxWidth = o.maxWidth;
}

var imgWidth = obj.width();
var imgHeight = obj.height();

var newWidth = maxWidth;

var ratio = imgWidth/maxWidth;

var newHeight = imgHeight/ratio;

obj.css({
height: newHeight,
width: newWidth,
});

});
}
});
})(jQuery);
[/js]

Let’s test out our plugin:
[js]
$(document).ready(function(){

$(‘#post img’).resizeimg();

});
[/js]

Congratulations! You’ve finished this long tutorial. I truly hope that you’ve learned something from it.

Author: (7 Posts)

Alexandre Smirnov is a web developer and designer who lives and works in California. He enjoys creating cool new stuff out of CSS3 and HTML5, and is convinced that Jquery is the meaning of life. He also regularly writes on his blog, DesignLunatic.com.

Comments