What is the best way to determine the height of an element after new content has been added through AJAX?

I have been working with a Jquery Mobile page and I am facing an issue when loading a form via AJAX. The plugin I am using to set the page dimensions calculates them after the AJAX call has completed and the layout has been updated. However, the height of the element that received the content is not being accurately retrieved (it shows around 169px instead of the expected 1200px).

Below is the code snippet I am using:

(inside plugin)
some: function(){

    var self = this,
    o = self.options,
    wrap = $('div:jqmData(wrapper="true").ui-page-active').last(),
    // elements
    panels = wrap.find('.ui-panel.ui-panel-active').filter(':not(.ui-popover)'),
    pages = panels.find('.ui-page'),
    contents = pages.find('.ui-content');

    // maxHeight contents
    for ( var i = 0; i < contents.length; i++){         
        ct = contents.eq(i);

        console.log( ct );
        console.log( ct.css("height") )
        console.log( ct.height() );
        console.log( ct.outerHeight() );    
    // max
    if ( ct.css("height") > parseFloat( o._iPadFixHeight ) ){
        o._iPadFixHeight = parseFloat( ct.css("height") ) + parseFloat( ct.css('padding-top')) +  parseFloat( ct.css('padding-bottom')) ;
        };
    }
     ...

When I do not use AJAX, everything works correctly. However, when adding content dynamically via AJAX, the retrieved values are inaccurate even though the consoles log after the AJAX call.

Question:
How can I reliably get the content element height after an AJAX update? I have tried setting a 10 second timeout after the AJAX call to wait for everything to load, but the height is still incorrect even after 10 seconds.

Any help would be appreciated!

EDIT:
Even though the consoles log after the AJAX load, it seems like the function is firing before the update, causing it to calculate based on pre-AJAX dimensions. I am considering re-firing the function using this:

$(window).on('dimensionchange', function(){             
    self.ome();
    })

And triggering it in my AJAX success handler.

EDIT2:
I have now fixed the issue. It turns out that the function was setting false values initially and not updating them after the AJAX call. Here's how I fixed it:

In the AJAX Success function:

...
// cleanup dimensions
$(window).trigger( 'dimensionclear');
...
window.setTimeout(function() {
   target.removeClass('.fade.in');
   // recalculate
   $(window).trigger('dimensionchange');    
   },250);

In my plugin:

$(window).on('dimensionchange', function(){ 
     self.ome();
     });
$(window).on('dimensionclear', function(){
     self.ome("clear");
     });    

And in the OME function:

// cleanup
if ( from == "clear") {
   contents.css({'height':'', 'max-height':''})
   return;
   }

Now it works perfectly.

Answer №1

This function is crucial for ensuring that all my div elements maintain their correct sizes. It is important to include something similar to this in your code, but make sure to remember to invoke it once the document is fully loaded.

function updateDivSizes() {
    /*
        Pre         : ready.js, self
        Post            : design.js->framing
        Author          : Enes Ü.
        Date            : 15:30, 05 May 12
        Summary         : adjusting div sizes accordingly
        Bugs/TODOs              : Some div heights are incorrect and need to be addressed. Priority=5
    */


    $("#right_menu").width($("#main").width()-$("#left_menu").width());
    $("#left_menu").height(getWinHeight());
    $("#top_menu").width($("#main").width()-$("#left_menu").width());
    $("#right_menu").height(getWinHeight()-$("#top_menu").height());
    $("#map_container").height(getWinHeight());
    /* 
     ******* more lines similar to the ones above...
     */

    setTimeout(updateDivSizes,100);
}

Answer №2

Utilize a cached element containing "wrap, panels, ct" to either refresh the cache variable or access it immediately

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

Configuring Angular routes based on service method invocation

I have my routes configured in @NgModule. I also have a service that determines which parts of the application to display based on specific conditions. I need to call this service and adjust the routes according to its output. Issue: The route configurati ...

Mastering Complex Selectors in ExtJS

In jQuery, I have code that fades out links which do not contain the text entered into a textfield (#searchServices) and fades in links that do contain the text. How can I achieve this in ExtJS? $('#searchServices').keyup(function () { if ( ...

What is the best way to assign a value to a button in Ionic/Angular?

Is there a way to bind the name and value attributes to a button? I am facing an issue with this and need a solution. I am attempting to achieve the following: <ion-button type="submit" color="primary" style="text-align:center& ...

What is the best way to adjust the height of a row in a Material UI table using CSS

I've been attempting to establish a row height of 30px for a table (https://material-ui.com/components/tables/), but it seems that the minimum I can set is 53. Why is this restriction in place? How can I adjust the row height to 30px using CSS based ...

Injecting Custom HTML Tag through JavaScript on Page Load in Google Tag Manager

When attempting to inject events into the data layer upon loading DOM pages on my website, I encountered an issue. Since I lack access to the website code and developers are reluctant to make additions, I decided to implement this through a custom HTML tag ...

Troubleshooting the Thumbs-Up and Thumbs-Down Voting System

My objective is to display multiple images on a single webpage and allow the general public to vote on them. I have implemented an AJAX command to hide the voting buttons and show a "thank you for your vote" message. This functionality works perfectly when ...

Switch out the HTML content within the JavaScript include

Here is the situation: <script type="text/javascript" src="http://xy.com/something.js"></script> This code snippet in my PHP/HTML file loads the entire something.js file. Inside that file, there are lines containing "document.write..." which ...

The jQuery UI Tabs Ajax feature seems to only be displaying content in the first tab that is

My jQuery UI tabs are set up to load their content using the ajax method: <div id="tabs"> <ul> <li><a href="/messages/inbox" title="Inbox"><span>Inbox</span></a></li> <li><a href ...

Transferring data between AngularJS and non-AngularJS environments

Within my AngularJS application, the $scope.mydata variable holds some important data within a controller. I am currently working on a regular JSP page without any AngularJS functionality, but I need to access the data stored in the scope variable (mydat ...

In the middle of one div, there are two additional divs positioned nearby

I am facing a challenge with positioning three divs within one container. I want one to be on the right, another on the left, and the third one at the center, but so far I have not been successful; <div id="durum3" style="width: 100%; height: calc(10 ...

Error discovered in Webpack syntax

I'm a newcomer to webpack and feeling lost on how to properly configure the settings. Here is my project structure: / -- /public -- /js -- app.js -- /css -- app.scss -- /node_modules -- /autoprefixer -- /babel-loader ...

Struggling to align list-items in a horizontal manner

I'm having trouble aligning the list-items in my horizontal navbar. Can anyone assist me in identifying the error? Below is the HTML code, which has a complex structure due to the use of the Wordpress thesis theme and Cufon for font replacement: < ...

troubleshoot using Visual Studio Code

Here's the scenario: I need to debug a project using VS Code. The project is usually started by a batch file and then runs some JavaScript code. Now, I want to debug the JavaScript code, but I'm not sure how to do that. If anyone has any instruct ...

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

Dealing with HTML and Escaping Challenges in jQuery Functions

Here is a string I have: var items = "<div class='item'><div class='item-img' style='background-image: url('images.123.jpg')'></div></div>" I am looking to update the inner HTML of a div: $ ...

Launching a new tab with a specific URL using React

I'm attempting to create a function that opens a new tab with the URL stored in item.url. The issue is, the item.url property is provided by the client, not by me. Therefore, I can't guarantee whether it begins with https:// or http://. For insta ...

Leveraging traditional code methods within AngularJs

With a multitude of older javascript functions for sign up/sign in operations through parse.com, I am considering integrating AngularJS for improved routing and other advantages. Is it feasible to establish an angular stack and encapsulate these functions ...

What are some alternative methods for updating content with ajax in ASP.Net web forms aside from using UpdatePanels?

In my experience with web UI development, I have gained a strong understanding of ASP.Net Web Forms over the course of four years. However, I have struggled to find an efficient way to update sections of a page using Ajax. I have tried various methods invo ...

Error occurs in ReactJS App when the state is updated in Redux only after dispatching the same action twice

Check out the following code snippet: ChartActions.js import * as types from './ChartTypes.js'; export function chartData(check){ return { type: types.CHART_DATA,check }; } ChartTypes.js export const CHART_DATA = 'CHART_DATA ...

Check if any element within a class satisfies the specified condition using Jquery

I am looking to determine if any element within a specific class meets a set of conditions. For example: $(document).on('click','.modalInner_form_nav', function(){ var input = $(this).parents('.modalInner_form').find(' ...