Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rerun Javascript when dom updates from ajax

I've been trying for a while to solve this problem I'm currently having, to no use untill now.

I have a main html file with a menu that loads content to a div trough ajax. The problem is that the loaded content (witch has a 'next' button to go to the...next dynamic loaded page) doesn't work, so I had to add a recall to the function I'm running on the parent page. Obviously this didn't went so well, because after clicking trough some of the links, I end up crashing the browser with more than 3000 request to the same function...

How can I make it so the function re-runs, or listens to DOM changes? And .on isn't working.

Script on the main file:

var din = function () {
    $('.dinMenu').on('click', 'a', function(event) {
        event.preventDefault();
        $('#dinContent').html('loading...');
        var $this = $(this);
        var module = $this.data("module");
        var folder = 'modules/module_' + module + '/';
        var href = $this.data("href");
        var url = folder + href;
        console.log(url);
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'html',
            cache: false
        }).done(function(data) {
            $('#dinContent').html(data);
        }).fail(function(jqXHR, textStatus, errorThrown) {
            $('#dinContent').html("Error!! File is not loaded");
        });
    });

    $(document).ready(function() {
     din();
    }); 

The HTML:

 ...
 <li class="dinMenu"><a href="#" data-href="child.html" data-module="1">link</a></li>
 ...
 <section class="panel content" id="dinContent" >
   <!-- start panel specific content -->
 ...

and the dynamic pages:

<footer class="subnav clearfix dinMenu">
  <a class="button next right" href="#" data-href="child.html" data-module="1">Next</a>
</footer>
<!-- end panel specific content -->
<script>
 din();
</script>

If I remove the script from the "child.html" file, nothing happens when I press next.

like image 388
RicNunes Avatar asked Mar 20 '23 02:03

RicNunes


1 Answers

Instead of

$('.dinMenu').on('click', 'a', function(event) {

which puts the event handlers on all the <li> elements, put the handler on the <body>:

$('body').on('click', '.dinMenu a', function(event) {

That way the event handler will remain in effect even when the menu is reloaded. There's no need to set it up again after an ajax reload, in other words.

like image 95
Pointy Avatar answered Mar 23 '23 09:03

Pointy