Here, I am sharing with you a small (however important) tip on how to assign the width and height of an Image using jQuery .width() and .height() methods. This is especially useful when you want to display thumbnail images on your web page. The images, let us assume, are significantly large and you want to set a standard size (width and height) for all the images.
Let us do it.
I have an image in a folder, whose original size is … I am not sure. However, I want to display the image with a size of 64px each, for the width and height, using jQuery. First, I’ll add the <img /> tag inside the <body> tag. When the page is ready, I’ll assign the “source” of the image along with some re-defined properties, such as, the width and height.
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> </head> <body> <p>The actual image is optimizied using jQuery width() and height() methods.</p> <img /> </body> <script> $(document).ready(function () { $('img') .attr('src', 'https://www.encodedna.com/images/theme/html5.png') .width('64px') .height('64px'); // CHANGE THE WIDTH AND HEIGHT AND SEE THE RESULT. }); </script> </html>
I am using the jQuery .width() and .height() methods to set the size of the image. We usually use these methods to either get or set the width and height of not just images, but other HTML elements too.
Remember, the methods take a parameter each when assigning or setting a value for the image (or any element). However, if you want to get the assigned values (width and height) of the image, you will simply define the method, without assigning any parameter.
console.log($('img').width());
console.log($('img').height());
Assign Image “width” and “height” using jQuery “Selector”
Similarly, you can assign the size of multiple images simultaneously, using either the image #id or .class as selectors. In the below example, I have add 3 <img /> tags, each with a class name defined.
<img class="size" /> <img class="size" /> <img class="size" />
<script>
$(document).ready(function () {
$('.size')
.attr('src', 'html5.png')
.width('64px')
.height('64px');
});
</script>
Dynamically add Image and Assign the “width” and “height”
Now, here is a more dynamic way to do what we were trying achieve in the above examples. I’ll not add the <img /> tag inside the <body> tag, instead define the image dynamically inside the <script> tag using jQuery. Along with it, assign the width and height of the images.
<script> $(document).ready(function () { $('<img />') .attr('src', 'html5.png') .width('100px') .height('100px') .appendTo($('body')); </script>
I am using jQuery .attr() method to first set the source of the image, next assign the width and height for the image, (like I have done in the above examples) and finally using “.appendTo()” method I am add the image to the web page. Similarly, you can add the image to an HTML element, such as a DIV.