Adjust the size of images using jQuery to perfectly fit the container dimensions

I am currently working on a script to automatically resize images that are too large for the container:

  $('img').each(function(i){
    var parent_width = parseInt($(this).parent().width()),
        image_width = parseInt($(this).width());

    if(parent_width !== image_width){
      $(this).width(parent_width).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parent_width + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    }
  });

The resizing functionality is working as expected. However, I want to display a message to the user showing the original size of the image, percentage of resizing, and the file size in KB.

For example:

This image has been resized to 400 x 300 (50%). Original image size: 800 x 600 and 75 KB. Click to view the original

Currently, I am only able to retrieve the width of the resized image (the height() method returns 0 for some reason).

Answer №1

Make sure to enclose your code within the $(window).load method

$(window).load(function() {
     // insert your code here
});

Answer №2

Give this a shot:

$('img').one('load', function () {

    var parentSize = parseInt($(this).parent().width()),
        imageSize = parseInt($(this).width());

    if(parentSize !== imageSize){
      $(this).width(parentSize).wrap(
         '<a class="resized-image" href="' + this.src + '">'
       + ' <span class="msg">'
       + '   This image has been resized to ' + parentSize + ' pixels'
       + '   and ' + $(this).height() + ' pixels'
       + '</span>'
       + '</a>'
      );
    } 

});

$('img').each(function () {
     //Check if image is cached by browsers, trigger .load()
    if (this.complete){        
         $(this).trigger('load');
    }
 });
​

Test it out in jsfiddler.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

There is zero gutter in Bootstrap

Is it possible to use the bootstrap grid system without any gutters? I want to have 3 columns in one row like this: http://prntscr.com/6gpmhm. I have shared the markup for the CSS I am using, which is the default CSS of the framework. <section class ...

Struggling to get the Hover feature on Link from Material-UI to function properly

I've been attempting to hover over Link from Material UI, but unfortunately, it's not working as expected. The CSS styles are not being applied for some unknown reason, and I can't seem to figure out why. Additionally, the Button class is al ...

Angular JS Profile Grid: Discover the power of Angular JS

I came across an interesting example that caught my attention: http://www.bootply.com/fzLrwL73pd This particular example utilizes the randomUser API to generate random user data and images. I would like to create something similar, but with manually ente ...

Tips for creating an array within an AngularJS Service and effectively sharing it across two controllers

I have two controllers, FirstController and SecondController, along with a service defined as follows: app.factory('Data', function(){ return []; }); In both controllers, I am utilizing the service in this manner: app.controller("FirstCont ...

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

"Fill the designated area on the webpage with data retrieved from an external script

In my current project, I am utilizing Angular and JQuery to enhance re-usability by setting the header and footer as partials. However, I encountered an issue where I needed certain javascript functions to be executed within the footer upon loading - a tas ...

Use CSS3 to conceal the form while displaying the default div

In my project, I am restricted to using only HTML5 and CSS3. Currently, I have a form that requires simulating the action of "sending form data". Upon clicking the submit button, the form should be hidden and a default div (#result) needs to be displayed. ...

looping through the iteration

Here is a link to my original plunker demonstration: http://plnkr.co/edit/9UBZ9E4uxAo1TXXghm1T?p=preview. In the case of div 4 (ng-if="show==4"), I am looking for a way to hide the particular div when the list is empty. Currently, each div is displayed fo ...

How come my header is not spanning the full width of the page?

Hey there, I've been struggling with a specific issue on my website and can't seem to find a solution anywhere else. The header on my site is supposed to stretch across the entire width of the screen, but for some reason, there's always a ga ...

Error encountered during the prerendering process on Vercel's Next.js build

While trying to compile my website on Vercel, I encountered a pre-rendering error during export. Does anyone know why this is happening and can provide assistance? Here is the link to my GitHub repository where all the code is stored: https://github.com/M ...

Leveraging Node.js alongside a Spring backend

As I delve into a project involving React on the frontend and Spring on the backend (both running on the same machine), an interesting question arises. Given that Spring backend operates independently of Node, and the web browser is used to showcase the Re ...

What is the best way to retrieve keys and values in jQuery after receiving an object through $.ajax and json_encode($arr) in PHP?

4 In my PHP code: $arr = array( 10=>"ten", 5=>"five", 2=>"two"); return json_encode($arr); When I use JS with $.ajax(): success: function(data){ console.log(data);} 5 After checking the console, it shows : Object {2: "two", 5: "five", 10: " ...

Ways to retrieve a value within a function and update a variable

Fetching data from the firebase database = firebase.database(); var ref = database.ref('urls'); ref.on('value', gotData, errData); function errData(err){ console.log('Error!'); console.log(err); } function gotData(d ...

"Customizing the color of the arrow in Bootstrap tooltips

Trying to customize tooltips in twitter-bootstrap, I set the template option of the tooltip with inline styles to achieve red tooltips instead of the default black color: $(document).ready(function(){ options = { container: 'body&ap ...

Having trouble with CSS box alignment issues in the top margin

I am working on customizing a CSS box for a navigation menu. Here is the current CSS code: .navigation-div { text-align:right; margin-top:14px; box-shadow:0px 0px 10px rgba(0,0,0,0.47); padding: 0; color:#E3E3E3; background-color: ...

Event dedicated to the selection of mobile options

I am facing an issue with binding an event to the options of a select tag on mobile devices. The code inside the click event handler doesn't seem to be working and I'm unsure of the reason behind it. My assumption is that perhaps the click event ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

When running the "react-scripts build" command and then serving it, the HTML files are being served instead

After successfully generating the build folder using react-scripts and running npm run build, I attempted to serve it locally with the npm package called serve by running serve -s build. The serve command started running on port 5000 without any issues. ...

Creating a function for loading dynamic content in XSLT can be achieved by following these steps

When I call the function collapseandexpand() for static elements only, it does not work. Now, how can I create the same function to handle dynamic content in xslt? Javascript Code: <script language="javascript" type="text/javascript> <xsl:text&g ...