Determining the Width of an Image Following the Application of a CSS Class Using Javascript

I have a custom script that is able to determine whether an image is in portrait or landscape orientation. Currently, the image is identified as being in landscape mode. My goal here is to crop and center the image using absolute positioning, specifying a height of 100% and applying a negative margin-left equal to half of the image's width.

Although I was successful in achieving the aforementioned tasks, I am currently facing a challenge. The images utilized in this scenario all have varying widths and heights since they are fetched from an API (specifically the Spotify API). As a result, I had to resort to JavaScript to accurately identify their respective widths. This process works perfectly fine until I apply the landscape class. Essentially, what happens is that the script divides the image's width before it is resized to fit within the constraints of the 250px x 250px #container div using the CSS properties assigned by that class.

My desired outcome is for the script to divide the image's width only after it has been successfully resized based on the attributes defined in the landscape class.

HTML

<div id="container">
  <img src="https://i.scdn.co/image/9c4880556288e2f4d098a104f5125e477611be32" >
</div>

CSS

#container {height: 250px; width: 250px; overflow: hidden; position: relative;}

.landscape {position: absolute; height: 100%; left: 50%;}

.portrait {width: 100%;}

JS

$(function() {
    var $img       = $('img'),
        $imgHeight = $img.height(),
        $imgWidth  = $img.width();  

    if ($imgWidth > $imgHeight) {
        $img
            .addClass('landscape')
            .css({
                marginLeft: '-' + $imgWidth / 2 + 'px',
            });
    } else {
        $img.addClass('portrait');
    }
});

Answer №1

Make sure to reevaluate the width after adding the class. Your current code is using a stored width value prior to applying the class. To fix this, you can use the following updated code snippet:

$(function() {
    var $img       = $('img'),
        $imgHeight = $img.height(),
        $imgWidth  = $img.width();  

    if ($imgWidth > $imgHeight) {
        $img
            .addClass('landscape')
            .css({
                marginLeft: '-' + $img.width() / 2 + 'px',
            })
    } else {
        $img.addClass('portrait');
    }
});

http://jsfiddle.net/d3u9tc0g/

Answer №2

Don't rely on the original value stored in $imgWidth. It's crucial to recompute it once the class has been added.

$img
            .addClass('landscape')
            .css({
                marginLeft: '-' + $img.width() / 2 + 'px',
            });

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

Tips for horizontally centering div elements with container and row class in Bootstrap 5

I am having trouble aligning the section properly in the center, and the div does not have a container class. Is there a bootstrap class that can help with alignment, or do I need to create CSS code to align the items in the div tag? <link href="ht ...

Transmit an Array using Ajax and retrieve it on an ASP Classic page

I am facing a challenge where I need to pass an array using AJAX on an ASP page. After trying to send it as GET method and checking the data being received, I noticed that only the LAST record of the array is being processed by ASP. How can I successfu ...

Check the input in the text box against the selected options to validate it

Currently, I am working on an add contacts page where I am facing the challenge of displaying an error message or highlighting input as invalid if a user tries to enter a contact name that already exists. It seems like one solution could be populating a s ...

Tips for ensuring consistent spacing between font icons within a navigation bar when using text with font icons as links

Below is the code I have implemented for a navigation bar: body { margin: 0; } .navbar { display: inline-block; background-color: #495057; width: 100%; } .navbar ul { list-style-type: none; text-align: center; float: left; } .navbar ul ...

Is there an alternative function that can be used in place of live() in jQuery version 1.26?

$('#data').find('div:eq(0)').append('<span class="show"> | show more</span><span class="hide"> | hide content</span>') $('div:gt(0)').hide(); $('.show, .hide').on('click', ...

Is it possible to create HTML tables without including paragraphs within the cells using docutils rst2html?

If my input rst file looks like this: +--------------------------------+ | Table H1 | +-------------+------------------+ | Table H2a | Table H2b | +=============+==================+ | a1 | b1 | +------ ...

Using the history.push() method from the Action Creator will update the URL without actually redirecting to a new page

I have a login page component that I've set up to redirect to another page after a successful login. However, even though the URL changes correctly, the page remains on the Login page. First, let me show you how I import the history module to be used ...

In a remarkable design with an array of buttons and an individual div assigned to each, a fascinating functionality unfolds. Whenever a

https://i.stack.imgur.com/emhsT.png When I click on the first "Respond" button, I want the adjacent text box to disappear. Currently, if I click on the first "Respond" button, both text boxes will disappear instead of just the first one. $('.comment ...

Submitting via ajax after resetting the form inputs

My form is being cleared through ajax, and I have validation for all the fields. The issue I am encountering is that when I enter data for one field and submit the form, the value entered in that field disappears. I want it to remain. Here is my ajax cod ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

CSS button with folded corner illusion and dynamic transitions

I have been using the code provided below to create a folded corner effect on a button, but I am having trouble with the white background that appears in the upper left corner of the button. Is there a class I can use to make this transparent so that the y ...

Incorporate JSON data into an existing array within Angular that already contains JSON data

I have a problem with adding new jsonp data to an existing array while loading more content near the bottom of the page. Instead of appending the new data, it replaces what's already there. function AppCtrl($scope, Portfolio, $log, $timeout, $ionicSl ...

Is there a way to programmatically emulate Firebug's inspect element feature using JavaScript?

Is there a straightforward method in JavaScript or any popular libraries like YUI or jQuery to allow users to interact with elements on a website, similar to the functionality of Firebug for developers? ...

Error: TypeScript is unable to find the property URL within the specified type. Can you help

Currently, I am honing my skills in TypeScript and encountering a problem. I am a bit confused about how to define the type for the URL when I am setting the mix here. Obviously, the URL is supposed to be a string, and this specific scenario is within the ...

Connecting your online store with Ecom Express through seamless API Integration

I'm currently working on integrating Ecom Express APIs into my project. Whenever I use postman to retrieve the AWB Number, it returns the JSON output like this: https://i.sstatic.net/k4r52.png However, when I attempt to implement the code on my page ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

Guide on Importing All Functions from a Custom Javascript File

As a beginner in learning Angular, I am faced with the task of converting a template into Angular. However, I am struggling to find a solution for importing all functions from a custom js file into my .component.ts file at once. I have already attempted t ...

When material skinning is enabled, the skinned animation mesh in Three.js mysteriously vanishes

After exporting an animated model from Blender, I encountered an issue with instantiating it in my project. Although I was able to create the THREE.Animation and model, I found that the animation was not working. I soon discovered that I needed to set skin ...

Is it possible to reset the existing localStorage value if we access the same URL on a separate window?

In my app, there are two different user roles: admin and super admin. I am looking to create a new window with a Signup link specifically for registering admins from the super admin dashboard. Is it possible to achieve this functionality in that way? Cu ...

Concluding remarks can be found at the end of the article

Is there a way to keep text aligned next to an image without it dropping down and disrupting the layout of the article? * { margin: 0; box-sizing: border-box; } * a:link { text-decoration: none; ...