The CSS effect fails to take effect following an AJAX response

After a successful ajax response, I am attempting to apply a jQuery .css effect. However, it seems that this process is not working as expected because I am trying to retrieve the height of a newly created element and then applying it to another newly created element. My goal is to move the .opts div to the bottom based on the dynamic height of the .col-4 div.

You can view the code pen here: https://codepen.io/Pancuatico/pen/abpOeZy

Upon opening the code pen, you can execute this code in the console:

$(".opts").css("margin-top",$(".col-4").height());
and observe that it works perfectly. But how can I make this work following a successful ajax response?

Edit

Below is my JavaScript code where I might have made a mistake:

$(document).ready(function(){
    loadImgs();
});

function loadImgs(){
    $.post("anurl.php", function(data){

        //Some data processing occurs here
        //...

        var out = "<div class='col-4'><img src='imgpathalt' alt='imgpath'></div>";
        out += "<div class='col-2'>";
            out += "<img src='imgpath2' alt='imgpath2alt'>";
            out += "<div class='opts'>";
                out += "<button>add</button>";
                out += "<button>rm</button>";
            out += "</div>";
        out += "</div>";

        $(".row").html(out);
        var col4Height = $(".col-4").height();
        $(".opts").css("margin-top",col4Height); //this does not work
    });
}

Answer №1

The issue here is that when you add the margin-top to those elements, the images are still loading. This means that at that moment, the height of .col-4 is only as big as the buttons. You need to wait for the images to finish loading before updating the margin to match the height of .col-4.

A more effective approach would be to generate the elements dynamically instead of including them in a string of HTML. By doing this, you can attach a load event to the image like so-

myImage.load(imgLoaded);

Then, update the margin once the image has loaded using this function-

function imgLoaded() {
$(".opts").css("margin-top", $(".col-4").height();); 
}

Of course, another way to achieve the desired result in your code is by using the html onload attribute.

$(document).ready(function(){
    loadImgs();
});

function loadImgs(){
    $.post("https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js",function(data){

        //...
        //Do something with the data here
        //This URL is just for testing purposes
        //...

        var out = "<div class='col-4'><img src='https://cutt.ly/IxR1RrQ' alt='https://bit .ly/3tI1rWa' onload='imgLoaded()'></div>";
        out += "<div class='col-2'>";
            out += "<img src='https://cutt.ly/IxR1RrQ' alt='https://bit .ly/3tI1rWa'>";
            out += "<div class='opts'>";
                out += "<button>add</button>";
                out += "<button>rm</button>";
            out += "</div>";
        out += "</div>";

        $(".row").html(out);

    });
}

function imgLoaded() {
    $(".opts").css("margin-top", $(".col-4").height();); 
}

Answer №2

Everything is functioning properly.

Check out the code snippet here

I have made some adjustments to the CSS parameters and they are now visible.


        var col4Height = $(".col-4").height();
        $(".opts").css("padding",'10px');  

        $(".opts").css("background",'green');  
        $(".opts"").css("top",col4Height);  

Also remember to use

$(".opts").css("top",col4Height);  
as it needs to be positioned absolutely


I would approach it differently though.

$(document).ready(function(){
    doWork();
});

async function loadImages(){}

async function doWork(){
    await loadImages();

    //perform additional tasks after images are loaded such as
    var col4Height = $(".col-4").height();
    $(".opts").css("padding",'10px');  

}

CHECK THIS

$(document).ready(async function() {
  await loadImgs();
 // Assume no images are loaded at the beginning.
  var imagesLoaded = 0
  // Count total number of images on the page once it has loaded.
  var totalImages = $("img").length

  // Increment count every time an image is loaded, when count equals total number of images,
  // call the allImagesLoaded() function.
  $("img").on("load", function (event) {
    imagesLoaded++
    if (imagesLoaded == totalImages) {
      allImagesLoaded()
    }
  })

  function allImagesLoaded() {
    console.log("ALL IMAGES LOADED");
     change();
  }
  });

async function change(){
 
    if($(".col-4").height() != 0) {
   var col4Height = $(".col-4").height();
      console.log(col4Height);
        $(".opts").css("padding",'10px'); //this does not work
   
        $(".opts").css("background",'green'); //this does not work
        $(".opts").css("margin-top",col4Height); //this does not work
    }
};
async function loadImgs(){
   await $.post("https://jsonplaceholder.typicode.com/posts",function(data){
        console.log(data);
        //...
        //Some process with the data here
        //Using that url for testing purposes
        //...
...

     
 
    });      
  var col4Height = $(".col-4").height();
  console.log(col4Height);

}

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

Ways to restrict a function to a single DOM element using either its id or class

This script is responsible for dynamically loading pages on my website. It works fine, except that it currently iterates over all anchor tags a on the site, whereas I want it to iterate only through my navigation menu. Here is the navigation menu: <div ...

Changing the color of a div while implementing a show and hide effect in JavaScript

I have designed a checkout system with three distinct parts - shipping information, billing information, and order confirmation. These sections are all on the same page, allowing for a seamless flow during the checkout process. Once a customer completes t ...

Attempting to retrieve the value of "id" using a "for...of" loop

I am seeking assistance with my auditTime function. In the loop using "for . . of", each element of the div HTML collection with the class name "time-block" should be iterated through, and the number value of that div's id should be assigned to the va ...

The jQuery Modal Dialog functions properly on the initial page load, but fails to work on subsequent pages unless manually refreshed

So, I've encountered an issue with my jQuery modal dialog. It's set up to remind non-registered users to sign up when they try to access user-only actions. Oddly enough, the dialog functions perfectly after a page refresh on THAT specific page. H ...

"Encountering consistent errors when attempting to upload files via ajax in ASP.NET

I'm attempting to perform an ASP.NET file upload using ajax. Here is the ajax call I have set up: $.ajax({ type: "POST", url: '/Home/Upload', ...

Tips for updating information when a button is chosen

Hello everyone, I need some help with a form that has three select buttons. The button labeled "Distribute" is already selected when the page loads, and it contains information about full name, password, and location. How can I use JavaScript to create a c ...

The transparency effect on the overlaying image gradually diminishes as the images transition in the jQuery slideshow on Internet

My slideshow smoothly transitions between images, with a logo positioned to partly overlay it. Everything looks great except for one pesky issue in IE6 - when the images change, the part of the logo that overlaps the slideshow also fades. I don't wan ...

Customize the layout of menu icon in HTML/CSS using FlexBox Grid

Recently, I have encountered an issue with the position of a menu icon on my website. The icon is displayed when the window reaches a certain size, but it is not aligned properly on the right side of the site. Ideally, I would like to use the "right" prope ...

Initiate the preloader function with a GIF loading image to display while my PHP script processes and retrieves data

This PHP file is responsible for downloading image and data files from the server. <?php header("Cache-Control: no-cache, must-revalidate"); //header("Expires: Tue, 25 sep 2012 09:00:00 GMT+5.30"); header("Content-Type: applica ...

Refreshing the Date Display with AJAX Response

Within a view, there is a DisplayFor connected to a DateTime field in the Model. After an AJAX call returns a Date to update the field, I am able to convert the AJAX date into a MM/DD/YYYY format. However, using .val to set the DisplayFor does not reflect ...

The persistent space between the navbar and the index page remains despite the suggested fixes provided

There appears to be a discrepancy between the navigation bar and the rest of the page. Despite my efforts to adjust margins, I haven't been able to resolve it. The system is prompting me for more details before posting this question, but I'm unsu ...

What is the best way to incorporate web components into a React Js project?

I am currently unfamiliar with web components. My main goal is to integrate Google Material Components into my React.js project. Google Material Web Component can be found here: https://github.com/material-components/material-components-web Is there a ...

Maintaining Scene Integrity in THREE.JS: Tips for Handling Window Resizing

My layout includes a div with a scene that looks great initially; however, as soon as I start moving or resizing the window, the scene overflows the boundaries of the div and goes haywire, almost filling the entire window. Are there any techniques or solu ...

What is the best way to add border-radius to an image while incorporating padding?

I am facing an issue with images that have white padding at the top and bottom. Please refer to the attached image. Whenever I try to apply the border-radius property to these images, the edges appear distorted. Is there a way to resolve this problem wit ...

Is there a way to remove a certain child category post from appearing in a parent category?

I'm having trouble with displaying related posts by category while excluding a specific category. I've tried different methods but none seem to work, and I'm not sure how else to approach this issue. <?php $categories = get_the_terms ...

Navigate to the specified URL once the Ajax function has completed successfully

I'm having trouble with opening a URL from an Ajax function. It seems like the URL is not being called. This is the code I am using: $(document).on( "click",".btndriver", function() { var id = $(this).attr("id"); var nombre = $(this).att ...

Issue with Jquery 1.10.2 not functioning properly on IE10 with JSON data

I am currently experiencing difficulties with parsing JSON data. The following function is causing errors: parseJSON: function( data ) { //Try to parse using the native JSON parser first if (window.JSON && window.JSON.parse) { retu ...

I need help setting up a link in HTML that redirects to the correct webpage when clicked. How can I make this happen smoothly?

<!DOCTYPE html> <html> <head> <title>______</title> <button class="btn about">About</button> <button class="btn socialmedia">Social Media</button></button> <button class ...

Enhancing an Image Gallery using CSS

Currently in the process of building a website for an upcoming event, and naturally, I need to create an event calendar. For inspiration, I have been referencing this example for its gallery layout and hover effects. However, I am hoping to customize thi ...

Activate the last div within the identical class

When I make an ajax call to fetch more results and append them to the existing ones on the same page, I want to display a scrolling spinner while the contents are being fetched. I am adding a div at the bottom of the fetched results like this: <div cla ...