1

I am using jQuery to calculate some sizings and add CSS to an element like this..

jQuery(document).ready(function(){
    jQuery(document.body).css("margin-top", jQuery(".myelement").height());
});

The problem is that the function fires before the myelement has actually appeared so cant get the height.

Is there a way to wait until / if .myelement is rendered before running the function? I did look at load but I think that is now deprecated

fightstarr20
  • 11,682
  • 40
  • 154
  • 278
  • 1
    How and when does you element appear that it's occurring after DOM-ready? Can you add a callback to the code that loads your element to do the resizing? – Cᴏʀʏ Aug 13 '18 at 21:15
  • 2
    Should we assume that `jQuery(".myelement")` is an image? – j08691 Aug 13 '18 at 21:16
  • myelement is actually a div containing some text, i think it is added afterwards using javascript but I have no control over that – fightstarr20 Aug 13 '18 at 21:23
  • 1
    with this few info I may suggest [Mutation Observer](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) even if it's expensive – gaetanoM Aug 13 '18 at 21:27
  • Just a quick FYI, while .load() is removed, you can use .on("load", fn) to attach to that event. Take a look at this answer: https://stackoverflow.com/questions/7434685/event-when-element-added-to-page. My only suggestion would be if you go the setTimeout route, use requestAnimationFrame instead. Mutation Observer is probably the cleaner approach if it is supported in all of the browsers you support. – Erik Nedwidek Aug 13 '18 at 21:31

1 Answers1

1

If .myelement is an image, you can use its load event to wait for it to be rendered.

jQuery(document).ready(function($) {
    $(".myelement").on("load", function() {
        $(document.body).css("margin-top", $(this).height());
    });
});
Barmar
  • 741,623
  • 53
  • 500
  • 612