Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onload after ajax loading

After returning to main content by ajax load, function onload didn't run. I can understand why, but how can I make it run in that condition?

<script type="text/javascript">
        onload = function() {
            if (!document.getElementsByTagName || !document.createTextNode) return;
            var rows = document.getElementById('chat').getElementsByTagName('tr');
            for (i = 0; i < rows.length; i++) {
                rows[i].onclick = function() {
                    $("#chat_main").load("chat", {
                       m: this.id,
                       ajax: 1 //here we are loading another page
                   });
                }
            }
        }
    </script>
    <script>
        function return_to_main() {
            $("#chat_main").load("chat", {
                ajax: 1 //here we trying to load back main page
            });
        }
    </script>

P.S. return_to_main() is binded on input type="button"

like image 694
sashaaero Avatar asked May 11 '26 00:05

sashaaero


1 Answers

You are binding to the window.onload call. It does not magically get called every time the page content is updated. It is only called once. You need to call a function every time you want the code to run. So when the Ajax call is complete, you would been to trigger it.

BUT You are using jQuery so use it.

There is no reason why you would need to bind to every row on the table. Use event delegation. Now when the content changes, you will still have the events bound.

$( function () {  //document ready
    var chatMain = $("#chat_main");
    chatMain.on("click", "table tbody tr", function () {  //listen for clicks on table row
        chatMain.load("chat",
            {
                m: this.id,
                ajax: 1 //here we are loading another page
            }
        );
    });
});
like image 103
epascarello Avatar answered May 12 '26 14:05

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!