Custom Jquery function is failing to position divs correctly within ajax-loaded content

I recently coded a custom function that efficiently positions absolute divs within a container by calculating top positions and heights:

$.fn.gridB = function() {
    var o = $(this); //UPDATED from var o = $(this[0]);
    o.each(function() {
        var a1top = o.find('.article1').position().top;
        var a1height = o.find('.article1').height();
        var a0top = o.find('.article0').position().top;
        var a0height = o.find('.article0').height();
        var a2top = o.find('.article2').position().top;
        var a2height = o.find('.article2').height();
        var a3height = o.find('.article3').height();
        var a4height = o.find('.article4').height();
        var a5height = o.find('.article5').height();
        if (a0height > a1height + a1top) {
            $('.article3', o).css('top', a0top + a0height + 20);
        } else if (a0height < a1height + a1top) {
            $('.article3', o).css('top', a1top + a1height + 20);
        }
        $('.article4', o).css('top', a2top + a2height + 20);
        $('.article5', o).css('top', a2top + a2height + 20);
        $('.article6', o).css('top', a2top + a2height + a5height + 40);
        $('.article7', o).css('top', a2top + a2height + a5height + 40);
        var lastChildPos = o.find('div:last-child').position().top;
        var lastChildHeight = o.find('div:last-child').height();
        o.height(lastChildPos + lastChildHeight + 20);
    });
};​

The container with the class ".fours" performs perfectly on window load. However, when triggered after an ajax infinite scroll load, it fails to accurately position the absolute divs inside the subsequent ".fours" container:

function loadArticle(pageNumber) {
    $('a#inifiniteLoader').fadeIn('fast');
    $.ajax({
        url: "wp-admin/admin-ajax.php",
        type: 'POST',
        data: "action=infinite_scroll&page_no=" + pageNumber + '&loop_file=loop',
        success: function(html) {
            $('a#inifiniteLoader').fadeOut('1000');
            $("#content").append(html); // Content will be loaded here
            $('.fours:last').preloader_index();
            $('.fours').gridB(); // UPDATED from $('.fours:last').gridB();
            $('.article a').on({
                mouseenter: function() {
                    if (!$('.preloader', $(this).parent('.article')).length > 0) {
                        $(this).stop().css('opacity', '1');
                    }
                },
                mouseleave: function() {
                    if (!$('.preloader', $(this).parent('.article')).length > 0) {
                        $(this).stop().css('opacity', '0');
                        $('.article-info', $(this).parent('.article')).stop().fadeTo(200, 0);
                    }
                }
            });
        }
    });
    return false;
}​

I am close to resolving the issue. When I include .fours:last in the gridB() function call post ajax success, only the top position of the divs is calculated disregarding the heights. Removing :last results in neglecting both top position and heights.

Any assistance appreciated.

UPDATE: Below is an example of the HTML related to this issue:

 <div id="content">
<div class="fours">
  <div class="article article0">
     <div><img src="url" /></div>
  </div>
  <div class="article article1">
     <div><img src="url" /></div>
  </div>
  <div class="article article2">
     <div><img src="url" /></div>
  </div>
  <div class="article article3">
     <div><img src="url" /></div>
  </div>
  </div>
<!-- Next ".fours" div loads here through ajax function -->
</div>

UPDATE 2: Modified the gridB function line to var o = $(this); from var o = $(this[0]); and adjusted the function call to $('.fours').gridB(); instead of $('.fours:last').gridB(); The script now correctly positions all absolute divs within the ajax-loaded sets but with values identical to the first set of articles. A more targeted approach required as :last does not suffice.

Answer №1

In response to the feedback given in your recent update, here is a suggestion on how you can refer to the last <div class="fours" /> that was added:

success: function(html) {
    var $html = $(html);                       // Wrap HTML content in a jQuery object.
    $('a#inifiniteLoader').fadeOut('1000');
    $("#content").append($html);               // Append the created object to the content.

    $html.preloader_index();                   // Use the same object for preloader index.
    $html.gridB();                             // Call gridB using the same object.

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

Guide on toggling the display of a div in JQuery

Hi everyone! I'm trying to figure out how to close a div that is open with the show() function. For example, I have a "div a" containing a hidden "div b". When I click on "div a", "div b" should appear. However, when I click on an [x] inside "div b", ...

Navigating through HTML content and extracting specific elements

After using an ajax call to retrieve the partialView HTML of a page, I need to extract information from the main div before displaying it. This data specifically relates to the size information in order to create a floating window. Here is the code snippe ...

Problem with Anular5 - "this" not functioning correctly inside of ready()

I am encountering an issue in graph.component.ts this.cContainer = cytoscape ( { ready: function(e) { this._dataService.setResultData(); } }); However, I am getting the following error message: ERROR TypeError: Cannot read property &ap ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

add a border to an image when it is hovered over

I'm having trouble getting the hover effect to work on my images. I suspect that I may be targeting the CSS hover incorrectly, and there could also be a conflict with the jQuery code that is attached to the images. Here is the link to the fiddle: ht ...

Achieving Full Height: Making one div occupy the entire height of another

Click here to see a jsfiddle example of what I'm working on. The jsfiddle above demonstrates the issue I'm facing. I am struggling to make the element with the ID #main_info fill the entire height of its parent element #main. My goal is to ensur ...

What could be causing my CSS navigation toggle button to malfunction?

My attempt at creating a toggle button for tablets and phones seems to be failing. Despite the javascript class being triggered when I click the toggle button, it is not functioning as expected... https://i.stack.imgur.com/j5BN8.png https://i.stack.imgur. ...

Can the color of a highchart graph be altered simply by clicking on the line?

Greetings! I am currently working on plotting a graph using highchart and I was wondering if there is a way to allow users to change the color of the plotted line by simply clicking on it and selecting a color from a color picker tool. I do not want to lim ...

Automatically submitting forms without having to refresh the page

I have been searching for answers online, but none of them seem to help me. Additionally, I am struggling to grasp the concept of Ajax. I need everything to happen on a single page without any refreshing until the entire form is submitted. <form id=" ...

Allowing horizontal scrolling in a table cell set to full width

I'm attempting to achieve the desired outcome by utilizing the code provided at What I'd like to know is why the scrolling function isn't working as expected. Instead of scrolling, it simply expands the table. To see the difference, try run ...

What are some clever ways to outsmart bootstrap rows?

Trying to find a way to work around Bootstrap rows. I have multiple col-..-.. items that I need to fit into one row, but modifying 8 complex .js files is not an option for me - and they refer to the children of the div I used as a bootstrap row. HTML manip ...

Using JQuery, you can make a $.get or $.ajax request to a PHP script on the server that needs to receive

A PHP function called functionexchangeRate($exchangeFrom, $exchangeTo) has been created with two parameters in mind. However, I am currently struggling to properly call this PHP script using Jquery's $.get function because I can't seem to figure ...

Exploring methods to reload a parent window from a child window using PHP

After opening a popup window from a modal, I am now trying to refresh the page where my modal is located. I have attempted to write some code that I found here, but it doesn't seem to be working. Here is an example of what I have tried: // This fun ...

The Material UI dialog box popped up against an unexpected gray backdrop

Currently, I am using Material UI in conjunction with React to create a dialog that appears when a button is tapped. This button is located within a table, which is displayed over a Paper component. The problem arises when I utilize the dialog with its def ...

What is the most dependable method for referencing a CSS class through programming?

Within my Sharepoint project, I am dynamically generating controls in the overridden CreateChildControls() method. I am uncertain which approach is more preferable when it comes to referencing the .css file: protected override void CreateChildControls() { ...

"Exploring the Interaction Between Solr, Tomcat, and CORS

Currently, I have Solr 4.3 running on Apache Tomcat 9 as a webapp for a CRM product to provide indexes. To perform a search on the indexes, I am querying Solr using the following URL: http://localhost:8888/solr-intranet-int/intranet_users/suggest?q=(surn ...

A guide on altering the color of a badge through programming

I am curious to learn how I can dynamically change the color of a badge in Angular. My goal is to initially set the color of the badge to white, and then if the percVLRiskTotal reaches a specific value, change the color to green as an example. CSS: <sp ...

Ways to input data into MySQL from a dynamically created row containing multiple selections?

tableX tabX_id name value ------------------------------------ Row1 25 XnameA 1.25 Row2 26 XnameB 4.85 Row3 27 XnameA 3.25 tableY tabX_id mytabX_id multiple_tabX_id ------------- ...

There was an issue encountered when trying to call a PHP file within an HTML table using Ajax and data.html

For a small project, I have various news items that need to be included from the "news_all.php" file into table data within the "dashboard.php" file. Due to the predefined root structure restrictions, using include('news.php') is not an option. I ...

Steps to correctly reset an XMLHttpRequest object

I'm currently working on a project where I send AJAX requests, receive responses, and replace text based on those responses. However, it seems like I may be missing a fundamental concept in my approach. request.onreadystatechange = () => { if (r ...