Struggling to adjust the width of a div accurately following the population of AJAX content

This particular piece of code is responsible for populating an inner div within an image slider by making an Ajax call :

$.ajax({
    type: "GET",
    dataType: 'json',
    url: $(this).attr('href')
}).done(function (result) {
    
    // add thumbnails to lower slider
    var correct_width = 0;
    
    for (var $i = 0; $i < result[1].length; $i++) {
        $('#lower_slider').append("<img src='" + result[1][$i]['image_thumb_src'] + "'>");
        
        // calculate $('#lower_slider') width
        $('#lower_slider').find('img').each(function () {
            correct_width += $(this).outerWidth();
        });
    }
    
    // set $('#lower_slider') width
    $('#lower_slider').width(correct_width);
});

The function of this code performs flawlessly the second time it's run - indicating that there might be some race conditions at play. How can these be resolved?

p.s - I am aware that a similar query has been raised before, but none of the solutions suggested have proven effective in my case.

Thank you.

Answer №1

It seems like the second attempt is successful because the requested images are already cached.

To ensure accuracy, consider calculating correct_width once all the images have fully loaded:

var correct_width = 0;
var imgArray = new Array();
var obj = this;

for (var $i = 0; $i < result[1].length; $i++) {
    imgArray[$i] = new Image();
    imgArray[$i].src = result[1][$i]['image_thumb_src'];
    imgArray[$i].onload = function() {
       $('#lower_slider').append("<img src='" + this.src + "'>");
       correct_width += $(obj).outerWidth();
    }
}

I have not tested this code myself, but it should function correctly.

Answer №2

After several attempts, I finally managed to make it function by incorporating a delay before the resizing and width calculation process:

var correct_width = 0;

for (var $i = 0; $i < result[1].length; $i++) {
    $("#lower_slider").append(
        "<img src=" + result[1][$i]["image_thumb_srcand "] + "'>"
    );
}

var wait = setTimeout(function () {
    $("#lower_slider")
        .find("img")
        .each(function () {
            correct_width += $(this).outerWidth() + 10;
            $("#lower_slider").innerWidth(correct_width);
        });
}, 1000);

I attempted other solutions but this was the only one that seemed to do the trick for me.

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

Executing JavaScript code upon successful form submission: An overview

I need help with my Asp.Net MVC web application. I am trying to implement a feature where some code runs on the successful response of an API method called upon form submission. Here is the current code snippet: @using (Html.BeginForm("APIMethod", "Confi ...

What value does a variable have by default when assigned to the ko.observable() function?

I am in the process of learning KnockoutJS and I have implemented code for folder navigation in a webmail client. In the view code, there is a comparison being made to check if the reference variable $data and $root.chosenFolderId() point to the same memor ...

Introduce a pause interval between successive ajax get calls

I've created a script that uses an ajax GET request when the user reaches near the end of the page. $(function(){ window.addEventListener('scroll', fetchImages); window.addEventListener('scroll', fetchNotifications); }); ...

Next.js displays component twice

When examining the first image, it appears that Next.js rendered this element twice. Initially, I suspected the issue was related to the tables I used. However, even after removing the tables and replacing them with just , the element still renders twice, ...

Styling with CSS: Utilize flexbox to adjust the layout of two elements, ensuring they

Trying to float an image to the right side of a paragraph is proving to be more challenging than anticipated. 100px +-------------------------+ +------------+ | | | | | ...

Utilizing Angular 2's *ngFor to conditionally wrap elements can be compared to organizing a layout with three columns in a Bootstrap row, then starting a

Currently I am facing a challenge with using *ngFor and it has me puzzled. My goal is to incorporate UIkit, but the same concept would apply to Bootstrap as well. <div *ngFor="let device of devices" > <div class="uk-child-width-expand@s uk-te ...

Learn the steps to dynamically adjust the size of a pop-up window in Sencha based on the content that is

This is the designated container where I plan to display text. The code resides within a modal (pop-up) and it's important for the pop-up to adjust its height based on the loaded text. Ext.define('Base.view.Notes', { extend: 'Ext.Co ...

Ways to eliminate the excess margin of ng-container from the webpage

When controlling two mat tabs with a statement, I encountered an interesting issue. Both mat-tab elements contain a card-list and are controlled with a statement in ng-container. Strangely, on the first tab, the card has a slight margin from the top when I ...

Adapt the CSS based on different screen sizes

I am currently developing a mobile application using angularjs and the ionic framework. My application is intended for both tablet and mobile versions. I have encountered an issue where I cannot use the same CSS for both the tablet and mobile versions. Is ...

"Ensuring Data Accuracy: Validating WordPress Fields with JavaScript

Can anyone provide assistance with this? I've been struggling for some time now. I am in need of a JavaScript code that can compare two fields in a contact form to ensure they match. For example, Phone Number and Phone Number Again. Both fields must ...

Utilizing JavaScript for parallax horizontal scrolling (identifying optimal 50% of screen)

I have successfully implemented this code for vertical scrolling: $('.flapleftclass').css('top',(0+(scrolled*0.5))+'px'); This method works well because I am referencing to the top position. However, when it comes to horizon ...

Implementing a postback without relying on AutoPostBack

My WebForm includes two drop down lists, where the options in the second list are determined by the selection in the first. Thus, when a user changes the category in the first dropdown, the second dropdown should display corresponding subcategories. This ...

Is there a way to modify the Javascript for this Contact Form to trigger a different action if a specific key is pressed instead?

I have been working on a Contact Form that integrates Google Scripts. Everything seems to be functioning well as it successfully sends emails and formats them properly in my inbox. However, there are two issues that I am encountering: -I want to exclude t ...

Verifying the type and quantity of an item

Looking at a piece of code where a specific condition is being checked, I'm curious to know why someone might want to skip this particular condition. var number = /^\d+/; var type = Object.prototype.toString.call(obj); for(var key i ...

Is concealing a button an effective strategy?

Recently, I decided to design a login form for my website. To quickly style the form, I opted to use Bootstrap through CDN. While working on the form, I encountered an issue with the button size as the device width changed. Initially, I applied the classes ...

From transitioning from AngularJS to the latest version Angular 8

I have an Angular application where I need to update some old AngularJS code to work with Angular table.html <table ngFor="let group of vm.groups" style="float: left"> <thead> <tr> <th><b>Sl. No</b ...

Having trouble making alerts or confirmation dialogs function in JavaScript

EDIT: Many thanks to everyone who helped fix this issue (: Your help is greatly appreciated! I've been struggling to get the alert, confirm, or prompt functions to work properly in my code. Here's a snippet of the code that's causing troubl ...

What is the most effective method for iterating through a JavaScript array?

Let's discuss an interesting way to work with JavaScript arrays. Consider the array below: const allRows = [ {id: 1, name: Name 1}, {id: 2, name: Name 1}, {id: 3, name: Name 1}, {id: 4, name: Name 1}, {id: 5, n ...

Troubleshooting: SVG Icon Fails to Appear in Bright Theme Due to CSS

My HTML is structured like this. <h2 class="mt-10 scroll-m-20 border-b pb-1 text-3xl font-semibold tracking-tight first:mt-0" id="know-your-life"> <a aria-hidden="true" tabindex="-1" href="#know-your- ...

The Ajax request fails to pass the value to the controller

I've spent the entire day debugging this method and I'm in need of some assistance. My goal is to make an API request and for each array it returns, I want to send a post request to my controller method. However, despite console.log showing the c ...