Unable to obtain the width of images on Chrome browser

I've been developing a basic slider that moves images from right to left. It's functioning properly on Firefox, but I'm encountering an issue with Chrome when trying to obtain the width of the images.

$(window).load(function() {

    // Loading images from a directory
    for (m = 1; m <= 5; m++) {
        $('ul').append("<li><img src='image_" + m + ".jpg'/></li>");
    }

    // Variables
    var ul = $('ul');
        li = ul.find('li');
        ul_width = 0;

    // Calculating total width of ul li
    $(ul).children().each(function() {
        ul_width = ul_width + $(this).width();
        alert(ul_width);
    });

...

In Chrome, the alert only shows a value of 50 because of the margin-left: 50px set for img. Therefore, I'm only receiving the margin size and not the actual image width as intended.

On the other hand, everything works smoothly in Firefox where I get both the margin size and image width correctly.

Could someone please advise me on how to address this issue? It's puzzling why the identical code functions perfectly in Firefox but encounters problems in Chrome.

Answer №1

Try this approach - it adds images to the document as soon as it's ready and waits to calculate their sizes after everything has finished loading:

$(function() { // using shorthand for $(document).ready();

var ul = $('ul');

for (m = 1; m <= 5; m++) {
    ul.append("<li><img src='image_" + m + ".jpg'/></li>");
}

var li = ul.find('li'),
ul_width = 0;

$(window).one('load', function() {

    li.each(function() {

        ul_width = ul_width + $(this).width();
        alert(ul_width);
    });
});
});

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

CSS Grid generates a unique container for every HTML element

My website's CSS code includes the following: *{ height: 100%; width: 100%; margin: 0; } .grid{ display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; } .grid div:nth-child(odd){ border: black 2px so ...

Exploring the synergies of Next.js and Node.js thread pooling

In my current project, I am utilizing nextJS with NodeJS and looking to implement child processes or workers. The code provided by NextJS itself is functioning perfectly. The relevant code snippets: NextJS with NodeJS Another resource I referred to: Nex ...

The combination of sass-loader and Webpack fails to produce CSS output

Need help with setting up sass-loader to compile SCSS into CSS and include it in an HTML file using express.js, alongside react-hot-loader. Check out my configuration file below: var webpack = require('webpack'); var ExtractTextPlugin = require ...

Guide to making a word validator using jquery

I am endeavoring to create a straightforward script that can parse the words within a string and compare them with a dictionary stored in a .txt file or an Array of correct words. The structure of the string I am working with looks like this: <data> ...

Checking the time using jQuery

Looking for some guidance on using jQuery to validate a Time field. My goal is to restrict users from entering times before 18:00. I know HTML5 field validation can achieve this, but I find jQuery offers more flexibility in formatting user responses. Plus ...

Creating Elements with Full Screen Width Instead of Parent Width Using CSS

Is it possible to make an element's width the full width of the screen instead of the parent's width? If so, how can this be achieved? <header> <nav class="navbar navbar-inverse navbar-fixed-top" data-tap-toggle="false ...

Encountering a React error when attempting to generate a URL for an image in Sanity

Server Error Error: The asset reference 'e173af30-fd2d-42ed-a364-d92a2cddf32c' is malformed. It should be in the format of an id such as "image-Tb9Ew8CXIwaY6R1kjMvI0uRR-2000x3000-jpg".https://i.stack.imgur.com/koC26.png https://i.stack.imgur.com/ ...

Is there a way to repurpose a function to work with both ids and classes?

My current code is affecting all elements instead of just the intended one. I've experimented with classes and ids, ruling out those as potential issues. I'm hoping for my JavaScript to target only the selected element, not all of them. Check ou ...

What are some strategies to enhance the performance of JavaScript pagination to ensure it functions effectively for varying numbers of pages?

Currently, I am working on building Vanilla Javascript Pagination. I encountered an issue where the pagination seems to work flawlessly only when there are precisely 7 pages. If the page count exceeds or falls below 7, some minor bugs start to surface. I h ...

The issue with jquery-ui draggable arises from the failure to access the property 'msie'

Having some difficulty getting jquery-ui draggable to work. I will be sharing my solution with you, and would love to know if this is the best approach? Before diving into my actual work, I decided to test it out. <script src="http://code.jquery.com/j ...

Update the radio options and link them to a particular identifier in both the database and the HTML tables

Currently, I have an AJAX request that generates a table with the following structure: | ID | Name | Radio | ======================================== | 123456 | One | Y,N | ======================================== | 78 ...

Determine the maximum value in the array using the Math.max method with

How exactly does Math.max.apply(null, arr); work? Let's take for example var arr = [45,25,4,65] ; Will it compare 'null' and '45' and return the maximum number between the two, like 45? After comparing, will it then compare t ...

Ajax request missing Github Basic OAuth token in authentication process

My personal access token is not being passed to the request when I make an ajax call. I keep receiving an error message saying API rate limit exceeded for 94.143.188.0. (But here's the good news: Authenticated requests get a higher rate limit.. I atte ...

Receiving an unhandled error of type when importing OrbitControl.js

I've been experimenting with Javascript to incorporate a glb 3d model into my webpage and so far, everything is going smoothly. However, once I try to import the OrbitControl.js (whether from my local directory or online), the browser throws me this ...

Combining load and change events in jQuery at the same time

Often times, I find myself needing to attach a behavior to an element both after it has loaded and after a specific event has been triggered (such as "change"). I believe the most efficient approach would be to combine these actions in one line: $('# ...

Complete guide on modifying CSS with Selenium (Includes downloadable Source Code)

I am looking to switch the css styling of a website using Python and Selenium. My initial step was to retrieve the current CSS value. Now, I aim to alter this css value. The Python code output is as follows: 0px 0px 0px 270px How can I change it from 0 ...

JSON with a null character

Despite spending an hour searching online, I feel a bit hesitant to ask this question. Can null characters (ascii null or \0) be used within JSON? I know they are not allowed within JSON strings, but my query is whether they can be included in the bod ...

Insight on the process of submitting interactive forms

I'm facing a challenge that I can't seem to figure out It's a form structured in HTML like this: <button (click)="addform()">add form</button> <div class="conten-form"> <div class="MyForm" ...

Expand the size of bootstrap-datepicker to fill the entire screen

I've implemented the plugin from https://github.com/uxsolutions/bootstrap-datepicker Check out the JSFiddle demo: https://jsfiddle.net/j3b089gr/ In my example, I have the calendar displayed along with the HTML code: <div class="row"> <di ...

Verify whether the session has been initiated and establish a global variable that can be utilized by JavaScript

I currently have the following arrangement: main.php page.php Whenever a user visits any of these pages, they experience an "introductory header animation". However, I want to ensure that this animation is only displayed on their initial visit and not w ...