Choose and adjust the size of images with a specific aspect ratio using jQuery

As I work on my Tumblr blog, I am experimenting with using jQuery to target photo entries (imgs) based on specific aspect ratios and resizing them accordingly.
To be more precise: If an image's width exceeds 250px, it should be resized so that the height is set to 250px with the width adjusted automatically. On the other hand, if an image's height is greater than 250px, it should be resized to have a width of 250px and the height set to "auto". Additionally, if the image is a perfect square, it should be transformed to a size of 250px by 250px. Here is the current code snippet that I am utilizing. Please bear with me if it appears convoluted; I simply experimented until achieving some desired outcomes...

<script>
$(document).ready(function() {
    $('.photo_post img').each(function() {
        var maxWidth = 250; // Maximum allowed width for the image
        var maxHeight = 250;    // Maximum allowed height for the image
        var ratio = 0;  // Aspect ratio calculation
        var width = $(this).width();    // Width of the current image
        var height = $(this).height();  // Height of the current image

    // Check if the current width exceeds the maximum limit
    if(height > maxHeight){
        ratio = maxWidth / width;   // Calculate the scaling ratio
        $(this).css("width", maxWidth); // Set the new width
        $(this).css("height", height * ratio);  // Adjust the height based on the ratio
        height = height * ratio;    // Update the height to match the scaled image
        width = width * ratio;    // Update the width to match the scaled image
    }

    // Check if the current height exceeds the maximum limit
    if(height < maxHeight){
        ratio = maxHeight / height; // Calculate the scaling ratio
        $(this).css("height", maxHeight);   // Set the new height
        $(this).css("width", width * ratio);    // Adjust the width based on the ratio
        width = width * ratio;    // Update the width to match the scaled image
        height = height * ratio;    // Update the height to match the scaled image
    }
});
});
</script>

However, I am encountering issues whereby this script does not work correctly for all photos.
Given my limited familiarity with jQuery, I would greatly appreciate thorough and thoughtful responses.

Answer №1

To ensure the image displays properly, you must determine if it is portrait or landscape and adjust its size accordingly.

Here is the updated JavaScript code:

$(document).ready(function() {
$('.photo_post img').each(function() {
    var maxWidth = 250; // Maximum width for the image
    var maxHeight = 250; // Maximum height for the image
    var ratio = 0; // Aspect ratio calculation
    var width = $(this).width(); // Current image width
    var height = $(this).height(); // Current image height

    // Portrait orientation
    if (height > width) {

        // Check if current height exceeds maximum height
        if(height > maxHeight){
            ratio = maxHeight / height; // Calculate scaling ratio
            $(this).css("height", maxHeight); // Set new height
            $(this).css("width", width * ratio); // Adjust width based on ratio
            width = width * ratio; // Update width to match scaled image
            height = height * ratio; // Update height to match scaled image

        }
    }
    // Landscape orientation
    else {

        // Check if current width exceeds maximum width
        if(width > maxWidth){
            ratio = maxWidth / width; // Calculate scaling ratio
            $(this).css("width", maxWidth); // Set new width
            $(this).css("height", height * ratio); // Adjust height based on ratio
            height = height * ratio; // Update height to match scaled image
            width = width * ratio; // Update width to match scaled image
        }
    }
});

});

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

Rotating Tetris pieces around an axis using HTML5 Canvas

I am currently working on a project and I have encountered a problem. When you press the UP key and hold it down, you will see what I mean: My goal is to make the object rotate around its axis instead of its current behavior. Please take a look at the co ...

Discovering and selecting the Business Manager choice from the Facebook Logout Menu using Selenium

Having some difficulty locating and selecting the Business Manager option in the Facebook logout menu. Can someone point me in the right direction? To find it, log in to Facebook > Click on the downward arrow icon on the top right corner of the screen ( ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

@font-face not functioning properly on mobile devices using Webkit

Struggling with getting @font-face to function properly across various mobile Webkit browsers. So far, it's not working on Safari for iPhone 3GS, default Android 2.2 browser, and Dolphin browser on Android. Interestingly, it does work seamlessly on a ...

Struggling with UI-Grid's single filter feature when dealing with intricate data structures?

I'm currently working with UI-Grid and facing a challenge while applying a filter to some complex data using their single filter example. Initially, everything runs smoothly when I use simple selectors. However, as soon as I attempt to delve one level ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

The proper way to incorporate HTML within JSON in Django Templates for safe usage

What is the best way to securely display JSON data in a Django web application? In my Django server, I create JSON data and then display it in a Django template. Sometimes, this JSON data contains snippets of HTML. While this usually works fine, if the &l ...

Using $watch to monitor the existence of a variable within the AngularJS scope

I'm working on a directive that displays alerts, and I want to set up a timeout function to run whenever the 'show' variable changes. How can I achieve this? When I tried invoking the link function, all the variables - show, message, and ty ...

The loading status will be updated once the data has finished being fetched

I have two action creators in my code - one for fetching data from an API and the other for managing the loading status. However, I am facing an issue where the loading status changes to false before the data is completely fetched. Here are the relevant p ...

Determine the central point of the cluster with the most concentrated xy data points

In my project, I have a 200 x 200 square grid where users can vote on the next desired position of an object within this space. Each time a user submits their vote, the XY position is added to an array. Currently, to determine the "winning" position, I ca ...

Convert your flexible designs into dynamic HTML with our Flex to HTML/A

Looking for a solution to transform Flex code into Html/Ajax code. Most of my Flex code includes datagrids, buttons, and text labels. ...

Tips for integrating PHP with HTML5 while developing a Blackberry native application that utilizes Blackberry websockets

I'm currently working on a basic HTML5 page that includes inline PHP script. I'm looking for advice on how to transform this app so it can be used with Blackberry WebSockets. For example, I want to develop a native app using HTML5. ...

JQuery's not operator is failing to successfully hide a div

Recently I have started learning jQuery. My goal is to hide the div with the id getLocation when another element is clicked. However, my current approach does not seem to be working as expected. $(:not("#getLocation")).click(function(){ if($("#getLoca ...

Comparison of Transform plugin and Syntax plugin within Babel

I am interested in incorporating Class properties into my webpack configuration. While following a tutorial on the website (www.survivejs.com), I came across two plugins being added to the .babelrc file: babel-plugin-syntax-class-properties and babel-plugi ...

Is there a way to align text in the middle while having different icons on each side?

Is there a way to center align the text in this image with minimal use of CSS/HTML? The icons on the left are causing it to be off center: https://i.sstatic.net/TKOYG.png Below is the relevant HTML and CSS for this top section: <div class="navbarhead ...

Iterate through nested objects in Javascript

I am having trouble extracting only the word from each new instance of the newEntry object. It shows up in the console every time I add a new word, but not when I assign it to .innerHTML. Can someone assist me with this issue? Full code: <style ty ...

Exploring SVGO CLI: A guide to inspecting SVGs across various directories

Currently, I am utilizing the SVGO CLI script to transform some icons within my project. Specifically, these icons are located in two separate folders - assets/icons/dark-mode and assets/icons/light-mode. My goal is to navigate through both of these folder ...

How to manage ajax URLs across multiple pages?

I have my website set up at http://example.com/foo/ within a directory, separate from the main domain. Through the use of .htaccess, I've configured the URLs to appear as http://example.com/foo/about/, http://example.com/foo/polls/, http://example.com ...

Issue with displaying a vTable component in VueJS / Vuetify

I am struggling with this basic HTML/Vue/Vuetify code snippet below, and I can't seem to get it functioning as intended. const { createApp, computed, ref, reactive } = Vue; const { createVuetify } = Vuetify; const ...

Exploring Relative Rotations in Three.js

I currently have a scenario where I have a THREE.Scene containing two meshes, namely meshA and meshB. Both of these meshes have been rotated differently. My objective is to take meshB out of the scene and attach it as a child of meshA, while maintaining it ...