0

I need to trigger a function AFTER my div #gMap has resized itself to my variable mapHeight. Using a phone I find the following is triggered too early.

$(window).resize(function () {
   var mapHeight = (viewport() - 85);
   $("#gMap").height(mapHeight);
   myNewFunction();
});

function viewport() {
    var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0], x = w.innerWidth || e.clientWidth || g.clientWidth, y = w.innerHeight || e.clientHeight || g.clientHeight;
    return y;
}

function myNewFunction(){
   alert("Div is resized");
}
Richard
  • 1,148
  • 3
  • 18
  • 33
  • Setting `height()` is immediate; there's no callback available or required. What do you mean by "triggered too early"? – Blazemonger Dec 08 '11 at 17:28
  • Most (but not all) browsers will fire `.resize` continuously as you resize the browser window. Is this the cause of your distress? – Blazemonger Dec 08 '11 at 17:34

1 Answers1

2

This will fire before the DOM has been updated. To get around this instead of the

myNewFunction();

try :

setTimeout(myNewFunction(), 0);

This should then fire after the DOM has updated with the new size.

extols
  • 1,762
  • 14
  • 19
  • Incorrect; the `.height` method is synchronous and no other code will be run until it's completed. – Blazemonger Dec 08 '11 at 17:29
  • Whlist changing a CSS property is technically synchronous there are some other factors to consider due to the way the javascript is executed. See this question for a more indepth discussion: http://stackoverflow.com/questions/779379/why-does-settimeoutfn-0-sometimes-help – extols Dec 08 '11 at 17:33
  • Thanks, unfortunately it doesn't quite work - the problem in particular is waiting for the div to be the same size as the variable (there seems to be a couple of seconds worth of delay) - is there not a way to trigger OFF the height the function? – Richard Dec 08 '11 at 17:47
  • mblase, `.height` is synchronous but it doesn't mean that the div has been repainted to the new height by the browser, it just means that the DOM has been altered with the new height. – aziz punjani Dec 08 '11 at 17:48
  • Richard: you wrote that this answer doesnt work - why did you mark it as answer? Is it working after all? – iappwebdev Dec 10 '11 at 13:15