When attempting to measure the width and height of images, Chrome and Firefox consistently produce a result of 0, while Safari is able to accurately

Struggling to assign a landscape or portrait class to images in a Wordpress gallery by measuring dimensions on load. Successfully tested in Safari, but encountering issues with Firefox and Chrome. Feeling stumped, any assistance would be appreciated!

jQuery(window).on('load', function () {

    jQuery(".blocks-gallery-grid img").each(function() {

        var aspectRatio = jQuery(this).css('width', 'auto').width()/jQuery(this).css('height', 'auto').height();
            console.log(jQuery(this).attr('src'));
            console.log(jQuery(this).width());
            console.log(jQuery(this).height());
        jQuery(this).data("aspect-ratio", aspectRatio);

        if(aspectRatio > 1) {
            jQuery(this).parent().parent().parent('li').addClass( "landscape" );

        } else if (aspectRatio < 1) {
            jQuery(this).parent().parent().parent('li').addClass( "portrait" );
        } else {
            jQuery(this).parent().parent().parent('li').addClass( "landscape" );           
        }
    });
});

Answer №1

$(document).on('ready', function() { 
    $(".blocks-gallery-grid img").each(function() {
        let _img = $(this),
            aspectRatio = _img.width()/_img.height(),
            parentLi = _img.closest('li');
            
        if(aspectRatio > 1) {
            parentLi.addClass( "landscape" );
        } else if (aspectRatio < 1) {
            parentLi.addClass( "portrait" );
        } else {
            parentLi.addClass( "square" );           
        }
    });
});
img{
  max-width: 100%;
}
li{
   padding: 15px; 
   box-sizing: border-box; 
   border: 3px solid;
}
.landscape{
   border-color: red;
}
.portrait{
   border-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="blocks-gallery-grid">
  <li>
    <img src="https://dummyimage.com/600x400/000/fff">
  </li>
  <li>
    <img src="https://dummyimage.com/400x600/000/fff">
   </li>
</ul>

Would you consider implementing a similar approach:

$(document).on('ready', function () {

    $(".blocks-gallery-grid img").each(function() {
        let _img = $(this);

        let aspectRatio = _img.width()/_img.height();

        _img.data("aspect-ratio", aspectRatio);

        if(aspectRatio > 1) {
            _img.parent().parent().parent('li').addClass( "landscape" );

        } else if (aspectRatio < 1) {
            _img.parent().parent().parent('li').addClass( "portrait" );
        } else {
            _img.parent().parent().parent('li').addClass( "square" );           
        }
    });
});

Additionally, assuming li is the direct parent element, you might be able to simplify your selectors using .closest().

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

Turn off HTML5 Audio

There are 4 <audio> elements on a webpage. The client has asked for them to be available sequentially. Meaning, the first audio should play, then the rest should remain disabled until the first one finishes, and so on. In addition, they want the au ...

Sync JSON object modifications with the DOM using jQuery (or potentially other libraries)

I am working on developing a web application that would be able to update the HTML elements based on changes in a JSON object. For instance, I have an unordered list with data attributes: <ul data-id="elements"> <li data-id="01">Element 01< ...

Any suggestions on resolving the issue of a white background in the Spotify embed code?

<iframe src="https://open.spotify.com/embed/track/6wsqVwoiVH2kde4k4KKAFU?utm_source=generator" width="500" height="100" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture" loading=&q ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

What is the best way to choose a column from a set of multidimensional inputs using JQuery

I am working with a table that contains checkboxes structured as follows: <input id="id_answer[text_singleline][0][1]" type="checkbox" value="1" name="answer[text_singleline][0][1]"> The second index [0] represents the row, while the third index [1 ...

Approaches to designing a reusuable Polymer component

As I start diving into the realm of Polymer web components, I am faced with the challenge of designing a product that can seamlessly integrate into multiple client applications or operate as a standalone application. This product happens to be a game with ...

jQuery random generator for creating two-dimensional arrays

Why do all rows always have the same numbers? They should be populated with random numbers. Also, how can I fix this issue? I remember seeing a solution here before but now I can't seem to locate it. var mapSizex = 5; var mapSizey = 6; var mapArray ...

I appear to be having issues with the pseudo-element. Is there something I am doing incorrectly? This relates to the first child

I initially tried to make the opening paragraph stand out by applying a red color, but unexpectedly, all elements on the page turned red. view image here <!DOCTYPE html> <html lang="en"> <head> <link rel="styleshee ...

Map will be visible correctly only when the window is resized

I'm currently working on a project that utilizes a map engine from a private company which I am unable to disclose. The initial system was built in JQuery, but we recently underwent significant changes and now have it running on AngularJS. One side ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

Picture cramped within a flexbox

I have a div containing an image that is larger than the screen, and I've set the div to be full width with overflow hidden. It works perfectly without creating scrollbars. However, when I try to use flexbox on this div, the image gets squeezed. Inter ...

Exploring the wonders of looping through arrays with JavaScript and jQuery

I am having trouble getting this function to work properly. My goal is to replace certain characters when a key is pressed. The code works fine using the variable `replace_list` instead of `replace_list["russian"]`, but I actually need different "replace ...

What is the best way to create a line of divs within a row?

I am attempting to create a series of divs, with each div containing two rows. Here is the code I have so far: index.html <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8> <title>Rows and Divs</title&g ...

How can I adjust the time in a range slider using AngularJS?

Currently, I am utilizing a Slider with draggable range in angular js for time selection. The Slider can be found here: https://jsfiddle.net/ValentinH/954eve2L/. I aim to configure the time on this slider to span from 00.00 to 24.00, with a 10-minute inter ...

How can I convert an HTML/CSS form into a PDF without altering its CSS design?

On my form, there are specific fields that users need to fill out. I'm looking for a way to automatically generate a PDF when these fields are submitted. Can anyone provide assistance with this? Currently, I've been redirecting the form data to ...

Unable to properly connect my CSS file to the header partial

I am struggling to include my CSS file in the header partial Here is the link I am using: <link rel="stylesheet" href="stylesheets/app.css"> This is what my directory structure looks like: project models node_modules public stylesh ...

Stylish CSS typography options for both Mac and Windows users

When browsing various websites, I've noticed that many of them showcase beautiful fonts without using images. Examples include The Firebug site and Happy Cog. It seems like web designers use CSS tricks and JavaScript to achieve this effect. I'm ...

What is the best way to establish personalized CSS styles specific to each subdomain?

I am in the process of establishing a multi-tenant application with a single instance and single database setup. The backend infrastructure is built using Ruby on Rails, while the frontend is handled by a separate AngularJS app integrated with a Rails fram ...

Primeng dropdown component with Right-to-Left layout support

Can the PrimeNG drop-down icon be positioned on the left side of the select? I attempted: <div class="ui-rtl" dir="rtl"> <p-dropdown></p-dropdown> </div> However, it did not function as expected. Are there any alternative so ...

How can I center align text after floating ul li elements to the left?

When creating a navigation bar with li elements floated left, the text also floats left. How can I center the text in the navigation bar? I have tried using text-align:center;, but it doesn't center the text on the y-axis. Some suggest using padding t ...