After .load in a div, js no longer works

1

When I go to some site page and try to run the functional script, it only works when I give f5, ie it does not work with .load in a div.

JS

$(document).ready(function(){
        var content = $('#content');
        $('a').live('click', function( e ){
            e.preventDefault();

            $("html, body").animate({
                scrollTop: $("#content").offset().top
            }, 300);

            content.html( '<div class="loading"></div>' );
            var href = $( this ).attr('href');
            $.ajax({
                url: href,
                success: function( response ){
                    var response = $( '<div>'+response+'</div>' );
                    var data = response.find('#content').html();
                    window.setTimeout( function(){
                        content.fadeOut('slow', function(){
                            content.html(data).fadeIn();
                            var title = response.find('title').text();
                            window.history.pushState( href, title, href );
                            document.title = title;
                        });
                    }, 500 );
                }
            });

        });
    });

HTML PART

//head, meta, links do js e css
    <body>
    //conteudo
    <div id="content">
    //conteudo carregado
    </div>
    </body>
    
asked by anonymous 02.02.2017 / 16:52

1 answer

2

When you change the content of the div with content.html(...) you are removing elements that had the link to your routine through the click event.

There are two simple ways to solve this problem:

  • Place your routine in a separate function and re-bind the event with content.on("click", suaRotina) ;

  • Add the event to an element that is not replaced, such as #content itself or body , thus content.on("click", "a", function() { ... }) . This way, when a a element is clicked, the event is passed to its parent elements until it reaches the #content that is listening to the event. More details

02.02.2017 / 17:51