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

Combining Bootstrap navbar with React Router for seamless navigation

I am new to using React and I am having trouble linking pages with Bootstrap navigation. I am attempting to use React Router DOM to navigate to different pages on click, but the app is not compiling because BrowserRouter is not being imported properly. I c ...

Connecting to a database using Vugen's Ajax TruClient feature

Recently, I've been experimenting with Ajax TruClient, but I'm struggling to find any functions that would enable me to connect to an Oracle database in order to retrieve information and compare it against the UI. Does anyone have any insights on ...

Click event in jQuery to change the background color of <td> element

I'm still getting the hang of jQuery, so please bear with me. :) The purpose of this code is to color a square with the selected color when clicked if it's white, and turn it back to white if it's already colored. It works fine except for a ...

jQuery functions are malfunctioning on Firefox, yet they are functioning properly on Chrome

Hey guys, can you take a look at this website using both Firefox and Chrome? I've noticed that jQuery doesn't seem to be working properly on Firefox. Any ideas why? ...

Is there a way to choose only the rows that are both even and not currently hidden?

I'm looking to change the row background colors in an alternating pattern. My goal is to target <td> elements on even rows that are not hidden. This is what I've attempted: $(".results-table tr:not(.hidden-row):even") .children("td") ...

Arranging two tables, one slightly misplaced from the other

I have been searching through various websites, but I cannot find a solution to the specific issue I am facing. I am attempting to create a web page with a table aligned to the left side while keeping the rest centered. However, when I align items in the ...

The jQuery button function is not compatible with Google Graph

Upon review below, I have successfully created the getChart() function. It functions properly when called independently, however, it fails to display the chart when enclosed within $(document).ready(function(){...}). The file is also attached for referen ...

Ways to increase the number of rows on datatables while utilizing ajax integration

My issue lies in trying to implement pageLength for my datatables using ajax. Instead of displaying 50 table rows per page as expected, it shows the entire dataset on each page. Here is the code snippet I am working with: JS $('table.dataTableAjax&ap ...

Replace the content within the iFrame completely

Is it possible to have a textarea where I can input HTML code and see a live preview of the webpage in an iframe as I type? For example, here is the code I'd like to write in the textarea: <!DOCTYPE html> <html> <head> ...

jQuery UI Drag and Drop problem with mouse positioning

I am currently working on a website that allows users to drag different "modules" (squares with information) from one location to another on the page using jQuery UI. However, I am facing an issue where when a module is dragged to a droppable zone, the sc ...

Achieving Bottom or Center Alignment for a Div within Another Div Using Bootstrap 5

I've been struggling to position my Title and CTA Button at the bottom (or center) of the main image div. I'm using Bootstrap 5.1 and have tried various d-flex methods without success. You can view my code on jsfiddle. Thank you in advance for a ...

jQuery cycle2 experiencing transition issues with anchor slides

Recently delved into using jquery cycle2 for the first time. Everything was smooth sailing when my slides consisted of images, but things took a turn when I switched to anchors. The scrollHorz transition effect that I specified didn't quite work out a ...

The counter is only incremented once even with multiple clicks

I am currently working on implementing a counter feature that allows the admin user of the website to update the counter by simply clicking a link. The functionality involves sending data through $.get to a mySQL record, updating the record accordingly, an ...

What strategies can I use to ensure that the navigation bar is responsive when viewed on a

Check out my CSS file here for the navigation styling. See the screenshot of my HTML file showcasing the navigation panel here. I'm seeking assistance in making my navigation responsive on all mobile devices, as it is currently not functioning prope ...

What is causing the Bootstrap accordion to not display content when clicked on?

As a beginner in web development, I am currently working on my very first website. One issue I'm facing is with incorporating an accordion-style card in my webpage. Although it allows me to click on different titles, the collapsed ones fail to expand ...

Incorporating fresh CSS styles through Selenium

I am attempting to showcase all the prices available on this page using Selenium and Chrome in order to capture a screenshot. By default, only 3 prices are visible. Is there a way to disable the slick-slider so that all 5 prices can be seen? I have tried r ...

Ways to center the percentage on the progress bar

I'm having an issue with positioning the percentage 100% in the center of the element. I attempted adjusting the spacing in the JavaScript code, but so far it hasn't been successful. Here is the current output for the code: http://jsfiddle.net/G ...

Backstretch.js experiencing issues with element functionality, but functioning correctly with body element

I'm having trouble getting backstretch to work on a div. It works perfectly when applied to the body with no errors, but when I try to apply it to a <div>, I get this error: Uncaught TypeError: Object [object Object] has no method 'backs ...

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 ...

The ajax success response transforms when using @html.raw

In my Razor viewpage, I have the following jQuery code: $(document).ready(function () { var listValues = @Html.Raw(Json.Encode(Session["list"])); $("#nsline").click(function () { alert(listValues) $.ajax({ type: "P ...