Determine the width of invisible images using JavaScript/jQuery

Please take a look at the jsFiddle

Every time I run it, I am trying to retrieve the width of the images, but the values I get are as follows (check in the JS console)

400 
0 
575 
533 
0
...

Some values are zero, and I can't figure out why. It seems random; different results each time. Even after refreshing the fiddle multiple times (F5), the width values vary. Sometimes accurate, sometimes just 0.

Even when I try running it locally (with images saved on my hard drive), the issue persists.

If anyone has any suggestions or insights into what might be causing this problem, please share!

Answer №1

The reason you are receiving a value of 0 periodically is because you are measuring the images before they have finished loading. When you attempt to measure an image that has not completed loading, it will return a width of 0.

To ensure that you get non-zero widths, you need to modify your code to check if the image has finished loading and wait for it if it hasn't:

if (this.complete) {
    console.log($(this).width() + " (didn't have to wait)");
} else {
    $(this).one("load", function() {
        console.log($(this).width() + " (had to wait)");
    });
}

For updated results, please refer to this Updated Fiddle.

Upon testing with a cleared browser cache in the embedded version of the fiddle, here is a sample of the output obtained:

var img = $(this);
img.one("load.showcase", function() {
    console.log(img.width() + " (had to wait)");
});
if (this.complete) {
    img.off("load.showcase");
    console.log(img.width() + " (didn't have to wait)");
}

Refer to this Fiddle for the updated version.

As explained, it is essential to hook the event first and then remove it immediately after to avoid missing notifications due to the multi-threaded nature of web browsers.

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

Having trouble with Javascript's JSON.stringify or PHP's json_decode?

I am attempting to send an array from JavaScript to PHP. JavaScript: var json = JSON.stringify(extraFields); url += "&json="+json; PHP: $json = json_decode($_GET['json'], true); foreach($json as $K=>$V){ echo "json".$K . "=" . $V ...

What is the best way to position the underline to appear beneath the second line in mobile view?

I have successfully incorporated a code to add a blue underline to the company name. However, in mobile view, the blue line appears on the first line. How can I adjust it so that it starts from the second line? Below is my CSS code: label { margin: 0; ...

Dealing with a 409 conflict situation involving a document in Node.js using Nano library

After conducting research, it has come to my attention that there are numerous document conflicts with couchdb. While exploring a potential solution in Updating a CouchDB document in nano, I discovered the following steps: Retrieve the document Store th ...

What causes my absolutely positioned element to disappear when using overflow-x: hidden?

I've been experimenting with the CSS property overflow-x: hidden on a container and noticed that it causes my element with position: absolute to disappear. To see this effect in action, check out this demo: https://codepen.io/Karina1703/pen/LYMzqEj ...

unable to connect css file to document

My index.html file is not reading the style.css file for some reason, even though it is linked. I have added the type and checked the path, but still facing issues. Can anyone help troubleshoot this problem? Thank you. https://i.sstatic.net/xxpBV.png htt ...

Encountering a situation where an empty value is being received from an

After submitting the form, I am receiving null values via ajax. Currently, I have 3 fields in the form and I am unable to retrieve any values from it. Please assist me in finding a solution. <table class="table table-hover table-centered m-0 table-bo ...

What is the process for importing DataTables using npm?

My attempt to import "datatables.net-select" using the usual method doesn't seem to be working. After checking the website, I found that the correct way to do it is: var $ = require( 'jquery' ); var dt = require( 'datatable ...

What steps should I take to make sure that the types of React props are accurately assigned?

Dealing with large datasets in a component can be challenging, but I have found a solution by creating a Proxy wrapper around arrays for repeated operations such as sorting. I am looking to ensure that when the data prop is passed into my component as an ...

Store live text field group in their respective index

I am working on a project that involves creating dynamic description textareas based on the value selected from a dropdown list. The dropdown list contains numbers 1 through 5, and for each number chosen, I need to generate corresponding textareas with ser ...

Is it possible to change the background color of a Bootstrap button using CSS overrides?

Desired Outcome https://i.sstatic.net/EjEXG.gif Actual Result https://i.sstatic.net/BmXYG.gif The goal is to toggle the red-background class, so that when hovering over the button-bullet, its background-color changes to #FCC1C5. Avoiding the use of .b ...

JavaScript Deviance

I am facing an issue with my JS code while trying to send form data to a .php file via AJAX. The problem occurs when the input fields are filled - for some reason, my client-side page refreshes and the php file does not get executed. However, everything wo ...

Difficulty encountered while implementing the if-else statement in raycasting operations

Currently, I am experimenting with raycasting to determine if my mouse is pointing at an object. The function seems to be working fine when the object is not being touched - it correctly prints out "didnt touch". However, when the object is touched, it s ...

Issues with Navigating through a Scrollable Menu

I'm having a difficult time grasping the concept and implementing a functional scrolling mechanism. Objective: Develop a large image viewer/gallery where users can navigate through images by clicking arrow keys or thumbnails in a menu. The gallery an ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Puppeteer does not display the TikTok comment input, whereas it is visible on the browser

Why can't I see the TikTok comment input on Puppeteer, but it's visible in the browser? Browser screenshot Puppeteer screenshot I've tried zooming out and adjusting the viewport with no success. I've written the code, but can't ...

What causes the TypeError: 0 is not a function error when using Array.from as a callback for Array.flatMap?

An issue arises when using Array.from as a callback with Array.flatMap, resulting in the error message: "TypeError: 0 is not a function" const x = ["12"].flatMap(Array.from) console.log(x) However, when used as a regular function, Array.from operates n ...

Styles for Material UI 5 class names

After upgrading from Mui 4 to 5, I am facing a challenge in using class names effectively. While the SX property allows me to apply styles to individual components, I am struggling with applying the same class to multiple components. In version 4, my code ...

Creating a visually engaging parallax effect in two columns with differing lengths that align perfectly at the conclusion

Recently, I came across an interesting layout technique on Apple's website that involves two columns with different lengths. As you scroll down the page, one column slows down to align with the other so that they both meet at the bottom. You can chec ...

Similar to session_start() and $_SESSION in Node.js/Express

I'm on a quest to discover the equivalent of session_start() and $_SESSION in Node.js/Express so I can store the current user's id in the session. Most tutorials and videos recommend using express-session, but I've come across a warning: ...

switch from ajax response to spring boot

I have encountered a situation that requires me to handle results obtained from an AJAX call in my Spring Boot controller. These results are displayed in a jQuery-accordion as per our customer's request. Now, the user should be directed back to the Sp ...