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

Issues with jQuery focus function in Internet Explorer 11

Is there a way to set the focus on an anchor tag using the URL? Anchor Tag: <a id='714895'>&nbsp;</a> URL: jQuery Code: try { if(document.URL.indexOf("?ShowAllComments=True#") >= 0){ var elementClicked = "#" +location.hre ...

Tips for integrating reCaptcha with AJAX using the .load() function

Looking to integrate reCaptcha with the jQuery '.load' ajax function for passing information to a PHP contact form. Managed to send name, subject, and other values using this method, but unsure about passing reCaptcha info. Encountering a PHP er ...

Toggle a button's activation based on the response from an HTTP request

I'm in the process of building an Angular application with .NET as the backend. I'm seeking advice on how to enable a button in Angular, either when an AJAX post request is successful or when the response is ready on the C# backend. appcomponent ...

Transforming an image by masking it to create a binocular-like view

I've been experimenting with creating a unique visual effect where an image is revealed through a binocular-shaped element that follows the mouse cursor. The circular part of the element moves along with the cursor, unveiling parts of the image as it ...

Is it possible to keep the vertical scrollbar always visible in jqGrid?

In my application, I have multiple jqGrids that may or may not have enough rows to need a vertical scrollbar initially. However, new rows can be added dynamically to these grids, eventually requiring a scrollbar. The issue arises when a grid does not have ...

When you hover, there is no writing cursor in sight

I'm looking for a way to display a label on an input field and have a writing cursor show up when hovering over the label. I am not interested in using a placeholder label. Do you have any simple solutions for this? See the code snippet below: JSFiddl ...

"A validation error occurred in the ABC Ajax request in an Asp.net application due to invalid

Here is my script: <script type ="text/javascript"> $(document).ready(function () { $('#<%=Button1.ClientID %>').click(function () { var ABC = 'TEST'; $.ajax({ type: ...

centering the text within the div for perfect alignment

I've been attempting to customize a Register form. My goal is to position the heading in the center of the div while having another login form located right beside it. Using flexbox, I styled them and then applied justify-content as center. Additiona ...

"Server request with ajax did not yield a response in JSON format

http://jsfiddle.net/0cp2v9od/ Can anyone help me figure out what's wrong with my code? I'm unable to see my data in console.log, even though the network tab in Chrome shows that my data has been successfully retrieved. Here is my code snippet: ...

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...

Include an option for whitespace characters when validating a file using regex

My text box has specific criteria for what is considered good or bad input. Examples of good input could include: GoodString GoodString88 99GoodString I want to avoid certain types of bad input, such as: Good*String Good&String However, I do want ...

The video on my site is refusing to play

I'm having an issue with a 2-second video that is not playing, yet when I tried a 10-second video it worked perfectly. Why is this happening? Could it be that HTML does not support videos that are shorter than 1-2 seconds? It seems like it's onl ...

What is the process of adding CSS effects to a button when a keypress activates it?

Do you have a CSS style that transforms the look of a button when clicked on-page? Want to extend this effect to when the button is activated via keyboard? (In essence, browsers allow activating a button by pressing Tab to give it focus and then hitting S ...

Restore checkbox to default setting

Is it possible to reset checkboxes in a form back to their initial status using javascript, PHP, jQuery, or any other method? Here is the code I am currently using: <form method="POST> <input type="text" name="name" id="name" value="default val ...

"Ensuring a DIV element has a height of 100% within

Is there a way to set and enforce a div's height to be 100% of the browser window, another div, or a table cell without resorting to complicated hacks found on Stack Overflow or other websites? ...

Transforming jQuery code to pure vanilla Javascript

For my project, I decided to convert my jQuery code into native JavaScript. The goal is to eliminate the dependency on jQuery and achieve the same functionality. The current setup involves two pages - page.html and side.html. The page.html document fetches ...

Is there a way to trim JSONP data to only obtain the year value

My current setup involves using an API to fetch data, which includes the release date of a game. '<h4 style="display:inline-block; padding-left:5px;" class="post-title">' + game.name + ' <span class="small">' + game.origin ...

Developing JSON with the use of jQuery

My latest project involves creating an application that converts HTML tables to JSON format. The code is functioning properly, but I've encountered an issue when the td or th elements contain inner components like span or other child elements. While I ...

Enabling droppable blocks within Jquery UI for div elements

I am facing a challenge in achieving my goal. Here is an example I have set up: http://jsfiddle.net/zs6US/ $('.draggable').draggable({ revert: 'invalid' }); $('#droppable').droppable({ accept: '.draggable' ...

Creating personalized validation for an AJAX popup in the MVC framework

In my MVC project, I am trying to implement AJAX popup with custom validation. I have created a CustomValidator class and overridden the IsValid() method. However, I am facing an issue where the custom validations are not rendering correctly within the pop ...