How to execute a function in javascript after an html element is loaded via AJAX without jQuery?

StackOverflow https://stackoverflow.com/questions/23661304

  •  22-07-2023
  •  | 
  •  

Question

I need to execute a given javascript function after a part of the page is loaded via AJAX. I have no control over how the page loads so trigerring an event from the page is not an option, I suppose I'll need to check the body for the element I need and execute after this element is exists.

I saw that I could do this using jQuery ".on" method, but my jQuery version is from before this feature was introduced so I can't use it. What's the best way to do this using no third-party libraries?

Here's an example using jQuery:

//bind to the body a "load" handler for elements that have class names of "hello"
$('body').on('load','.hello',function(){
  alert("Hello is fully loaded, proceed with your program logic");
})

PS: related question that I've read before posting this one. How to bind a function to Element loaded via Ajax

Was it helpful?

Solution

You can create a function to call when the elements are loaded, and another function to check if they are loaded at an interval. Then attach the load checking function to the body's onload attribute. For example:

<body onload="checkLoaded()">

<script type="text/javascript">
    var afterLoaded = function() {
        // code to execute once elements are in place
        console.log("Elements loaded.");
    };

    var checkLoaded = function() {
        var interval = setInterval(function() {
            if(document.getElementsByClassName("hello").length) {
                clearInterval(interval);
                afterLoaded();
            }
        }, 1000);
    };
</script>

Plunker

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top