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

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

Running the command "nexrjs create next-app" successfully generates all the necessary directories for the

After trying to install NextJS using both methods npm install next react react-dom and npx create-next-app appname, I noticed that my project directories are different from what they are supposed to look like: Instead of having pages, api(_app.js, index.j ...

Solving the Issue of Handling Custom Events in Javascript

I've been experimenting with a simple CodePen that features a basic table with three rows. I'm trying to attach event handlers to each row in the table and trigger the event by pressing a button. However, I'm facing an issue where the attac ...

Ways to determine whether a DOM textnode is a hyperlink

Is there a more foolproof method for determining if a DOM textnode represents a hyperlink? The code snippet below currently only checks if the node is directly enclosed in an anchor tag, which may not be sufficient if the <a> element is higher up i ...

How can we use jQuery to change the format of a

I'm working on a project where I want the calendar to display the date that the user picks. Right now, my "{{date}}" is in the format 2016-01-11, but it keeps showing one day before the selected date. I would like it to display as mm/dd/yyyy. I belie ...

JavaScript breaks when using jQuery Ajax to pass an email to a PHP script

Whenever I try to pass variables to my mail.php script for email composing, the script breaks down as soon as I enter an email address. It seems like the email is automatically converted to a URL, causing my JavaScript to crash. Am I misunderstanding some ...

Utilizing Zend JSON encoding for seamless integration with JavaScript

I'm currently working with the Zend Framework. My objective is to pass JSON data from the controller to JavaScript. I have a simple array: $array = array('a' => 1, 'b' => 2); After encoding this array into JSON format: ...

What is the best way to apply an animation class to a modal upon clicking a button?

When I click the "x" button on the modal, I want the animation to occur. However, what currently happens is that the modal closes without the animation. Then, upon reopening the modal, the animation occurs without any clicking involved. Below is my curren ...

Struggling to make `align-items="baseline"` function properly

I'm encountering an issue with alignment in my sandbox project. Specifically, I want the bottom of texts with different font sizes to be on the same y axis but I can't seem to figure out how to make it happen. Check out this picture to see exact ...

Obtain the text content of a div using JavaScript

Hello, I am new to Javascript! I have a table structure that looks like this: <table id='master_tbl'> <tbody> <tr id="master_hr'> <td class="myclass"> <table> <tbody ...

What is the significance of default parameters in a JavaScript IIFE within a TypeScript module?

If I were to create a basic TypeScript module called test, it would appear as follows: module test { export class MyTest { name = "hello"; } } The resulting JavaScript generates an IIFE structured like this: var test; (function (test) { ...

Encountering a CORS issue specifically on the client side of a Next.js application when interacting with an API gateway

I've been struggling with this issue for a week now and can't seem to fully describe it. I have a FastAPI server running as a Lambda connected to API Gateway. https://i.stack.imgur.com/S5Zx9.png Both FastAPI and API Gateway have CORS enabled, b ...

How to stop font-family and letter spacing from affecting the margin of div and ul elements in CSS

I'm facing a challenge with aligning a rotated div and an unordered list in a container. Adjusting the margin of either element does the trick, but changing font-family or letter-spacing globally affects the spacing between the two. Check out this JS ...

Struggling with the task of assigning a glTF item to a separate layer within Three.js

Exploring the use of layers in Three.js. This script includes a sphere, a triangle, and a glTF object (car). I activated a second layer: camera.layers.enable(1); Assigned the sphere, triangle, and glTF object to layer 1: car.layers.set( 1 ); sphere.lay ...

Retrieving complete credit card information with the help of JavaScript

I've been grappling with extracting credit card data from a Desko Keyboard, and while I managed to do so, the challenge lies in the fact that each time I swipe, the card data comes in a different pattern. Here is my JavaScript code: var fs = require ...

How can I pass a string value from C++ to JavaScript in a Windows environment using Visual Studio 2008?

In my current project, I have successfully implemented an IDL for passing a string value from JavaScript to C++. The JavaScript code effectively passes a string value to the C++/COM object. [id(1), helpstring("method DoSomething")] HRESULT DoSomething([in ...

Is it possible to submit a form using AJAX in WordPress without relying on WordPress functions?

As I work on constructing a website using Wordpress, I am encountering an issue with submitting a form via ajax. I'm wondering if it's possible to achieve this without relying on Wordpress functions. Currently, my code runs without errors and dis ...

Tips on storing information within a Vue instance

Seeking a simple solution, all I need is to save data retrieved after an AJAX post in the Vue instance's data. See below for my code: const VMList = new Vue({ el: '#MODAL_USER_DATA', data: { user: []//, //userAcc: [] }, met ...

Why is the autocomplete minlength and maxheight not functioning properly in MVC?

After entering a value in the text field, data from the database appears but adjusting the height and width of the list box seems to be a challenge. I have set the parameters like minLength: 0, maxItem: 5, but it doesn't seem to make a difference. ...

The updated Bootstrap 4 carousel is only working halfway as expected when attempting to double it up, causing the scroll loop to stop functioning

Discovering a fantastic carousel modification was an exciting find, which can be accessed Here. However, when attempting to place two carousels on one page, issues arose with the scrolling functionality. While I managed to make them operate on the correct ...