2

I have the following code that uses jquery to dynamically update a page once its been loaded from a URL

$(document).ready(function() {
        var htmlattri="background-color:red;";
        $("body").attr("style", htmlattri);
        $("#navbar").append('<div id="test" style="position: absolute; left: 0px; top: 0px; z-index: 3000; height: 20px"><input type="button" value="Back" onclick="window.history.go(-1)" /></div>')
    });

The problem I have is that the #navbar element is built via ajax (non JQuery) which happens after the $(document).ready has fired.

Is there a way to get this to fire once the page is fully built ?

I don't have control of the pages source code.

user1513388
  • 7,165
  • 14
  • 69
  • 111

2 Answers2

0

Put whatever code you are trying to execute in the success callback of the ajax call, after you have built up the #navbar. You cannot 'move' the $(document).ready() call, it will always execute when the dom has been created

andy mccullough
  • 9,070
  • 6
  • 32
  • 55
0

How about $.Event?

$('body').on('wearedone', function(){
    console.log('hello!');
});

$(document).ready(function() {
    var htmlattri="background-color:red;";
    $("body").attr("style", htmlattri);
    $("#navbar").append('<div id="test" style="position: absolute; left: 0px; top: 0px; z-index: 3000; height: 20px"><input type="button" value="Back" onclick="window.history.go(-1)" /></div>');

    // this is where we "reimplement" $(document).ready
    $('body').trigger($.Event('wearedone'));
});
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • I think if `$('body').trigger($.Event('wearedone'));` is executed right after `$("#navbar").append('...');` fires, it won't wait until DOM rendering is done. – Yan Yang Mar 31 '16 at 12:39
  • True. But, since js is not *async*, it will wait for the dom to render. no? – Unamata Sanatarai Mar 31 '16 at 12:40
  • So if you are using AJAX to construct the navbar, just add the `event` in `success:function(r){(...) event}` – Unamata Sanatarai Mar 31 '16 at 12:42
  • It's easy to judge when AJAX succeed, but I didn't find a way to judge if DOM render finished. I have asked this problem but no solution till now: http://stackoverflow.com/questions/31935005/whats-going-on-with-dom-after-orientationchange-event – Yan Yang Mar 31 '16 at 12:44
  • how about this one http://stackoverflow.com/a/2844704/2119863 or this one http://stackoverflow.com/a/11546242/2119863 ? – Unamata Sanatarai Mar 31 '16 at 12:45
  • Hmm..This does'nt make sense to me. A better description of the problem would be a login page whereby the form is rendered using ajax. How do you determine that the page is complete and the elements are available for updating ? – user1513388 Mar 31 '16 at 15:07