The jQuery function does not make use of the variables provided

I came across a helpful code snippet on stackoverflow for determining if an image is portrait or landscape oriented, and applying CSS width and height formatting accordingly.

However, after successfully implementing the code (hence all the $LSC references), I noticed that it immediately defaults to the "else" condition and applies the same styling to all images (setting width to auto and height to 100%).

My question is, what adjustments need to be made to the code in order for it to accurately compare the width and height of the images?

var $LSC = jQuery.noConflict();

$LSC(document).ready(function(){

    $LSC(".pg-cat-image").each(function(){    
        var real_width = $LSC(this).width();
        var real_height = $LSC(this).height();
        var parentwidth = $LSC(this).parent().width();
        var parentheight = $LSC(this).parent().height();

        var ratioParent = parentwidth / parentheight;
        var ratio = real_width / real_height;    

        if (ratioParent < ratio) {        
            $LSC(this).css({'width' : '100%', 'height' : 'auto'});
        } else {
            $LSC(this).css({'width' : 'auto', 'height' : '100%'});
        }
    });

});

Answer №1

Why involve the parent container when you can simply compare the width and height of the image itself?

let $ = jQuery.noConflict();

$(document).ready(function(){

    $(".pg-cat-image").each(function(){    
        let realWidth = $(this).width();
        let realHeight = $(this).height();  

        if (realWidth > realHeight) {        
            // The image is landscape
        } else if (realWidth < realHeight) {
            // The image is portrait
        } else {
            // The image is square
        }
    });
});

Answer №2

It is likely that your jQuery code is executing before the images have finished loading, leading to incorrect calculations of widths and heights for the image resulting in 0 values. Since the parent element is most likely a block level element with a set width, it explains why the calculation always falls into the "else" section.

To resolve this issue, consider enclosing your code within $(window).load(function() {}); instead of document ready. This ensures that the script waits until the entire page, including images, has fully loaded. More information on the load event can be found here.

$(window).load(function() {
    // This will execute after the complete page has loaded, including images
});

Therefore, you can modify your code as follows:

$LSC(window).load(function(){

    $LSC(".pg-cat-image").each(function(){    
        var real_width = $LSC(this).width();
        var real_height = $LSC(this).height();
        var parentwidth = $LSC(this).parent().width();
        var parentheight = $LSC(this).parent().height();

        var ratioParent = parentwidth / parentheight;
        var ratio = real_width / real_height;    

        if (ratioParent < ratio) {        
            $LSC(this).css({'width' : '100%', 'height' : 'auto'});
        } else{
            $LSC(this).css({'width' : 'auto', 'height' : '100%'});
        }
    });

});

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

.class selector malfunctioning

I'm currently developing a card game system where players can select a card by clicking on it and then choose where to place it. However, I've encountered an issue where nothing happens when the player clicks on the target place. Here is the li ...

The time parameter in jQuery's ScrollLeft animation method seems to be disregarded

Hey everyone, I'm having trouble understanding this: thumb.animate( {'scrollLeft': active.width()*3}, 'slow' ); The scrolling works fine, but the "slow" parameter seems to be ignored. Instead of moving slowly, it moves instan ...

Using an ASP.NET control along with jQuery within a standalone .js file

I recently created a jQuery voting script that functions perfectly when the code is kept within the header of the page. However, I am interested in transferring it to a separate .js file and simply including this .js file at the top of the page. Strangely, ...

Angular Fragmentary Perspective

I have a lengthy form in angular that I am currently working on. I'm wondering if there is a way to divide it into multiple views and then link each of them back to the main view. <div class="container"> <div class="row" id="part1"> ...

The problem with the Bootstrap Navbar Dropdown is that it opens up within the confines of

I have created a navigation bar using Bootstrap 4 and included the .navbar-bottom class to enable scrollbar functionality when there are more menu items than the total width of the page. However, an issue has arisen where the Bootstrap 4 navbar dropdown o ...

Linking together or organizing numerous JavaScript function executions in instances where the sequence of actions is crucial

I have implemented a web api method that conducts calculations by using a json object posted to the method. I believe that a jquery post is asynchronous. Assuming this, I want to be able to link multiple calls to the js function invoking this api method in ...

Transforming the header to function similarly to the address bar in the Google Chrome mobile app

I have managed to create a fixed header that appears when the user scrolls up and disappears when they scroll down. However, I want it to behave like the address bar on the Google Chrome mobile app - remaining stationary until the top of the window reaches ...

Retrieve information from MySQL database with jQuery upon button click

After fetching multiple data rows from a MySQL database and displaying them in a table, I want to include a button in the last column of each row. The unique ID for each button will be retrieved from the database. When a user clicks on any of these buttons ...

The border color of the text input is not changing as expected when in focus

Is there a way to change the border color of a text input field to blue when it is not selected and then change it to orange when the field is selected? input[type="text"]{ border: 1px solid blue; } input[type="text"]:focus{ border: 1px solid ora ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

"Using jQuery to create a regex pattern for validating usernames

I need assistance creating a regex pattern for usernames that must follow the criteria below: Usernames can only include a-z, A-Z, 0-9 and - (hyphens); Usernames cannot be entirely composed of digits or hyphens but can contain characters; The first ...

jQuery for Special Characters

I am currently facing an issue with the character &gt; in my jQuery datatable. Strangely, it displays '>' correctly but when I click on a row, the character &gt; appears and I am feeling frustrated. Is there any solution to this probl ...

If the checkbox is selected, retrieve the product name and price and store them in an array

If the checkbox is checked, I want to retrieve the service name and its price in an array. To get the values of the selected items (i.e. service name and its price in an array), please explain how I can achieve this. $(document).on('click', &apos ...

enhance image visibility on hover

I am trying to create a zoom effect on mouseover, but I am facing an issue where the height is set to 'auto' causing the zoomed-in image to overflow from the div and increase in height. I need to maintain the height as 'auto' for respon ...

What is the best way to implement a custom SVG icon within the Vuetify v-icon component?

Is it possible to utilize the v-icon component in Vuetify to display a custom icon that has been defined as an SVG in a file named my-icon.svg? This SVG file is located within the public/img directory of my project. How can I reference this file inside t ...

What is the reason my hyperlinks are not clickable?

I'm working on a project that checks if a Twitchtv user is live streaming and provides a link to their page. The streaming part is working correctly, but I'm having trouble making the username clickable. Even though the URL is valid and the page ...

Why is my console showing a SyntaxError with JSON.parse and an unexpected character?

I am facing an issue. When I attempt to call a PHP page for some data with specific requested parameters using AJAX asynchronous call, I encounter the following error: SyntaxError: JSON.parse: unexpected character var jsonData = $.ajax({ u ...

conceal the spinner loading animation once the script has finished executing

I'm having trouble displaying the spinner at the beginning of an AJAX call and hiding it once the call is complete. Unfortunately, I cannot seem to hide the spinner after the script has finished executing. Any suggestions or ideas on how to solve thi ...

When the value equals 25

I am seeking to implement a text field where users can input a number, and based on whether it's correct or not, display "image a" for the correct answer and "image b" for an incorrect one below the text field. I want users to have multiple attempts u ...