After . load on a div, js no longer works

Asked

Viewed 280 times

1

When I go to some page of the site and try to run the functional script, it only works when I give F5, IE, it does not work with . load on 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 );
                }
            });

        });
    });

PART OF HTML

//head, meta, links do js e css
    <body>
    //conteudo
    <div id="content">
    //conteudo carregado
    </div>
    </body>
  • You’re making $("#content") and has <div class="content">. Would not be $(".content") or else <div id="content">

  • This, I’ll edit, this right in my file, only here I didn’t notice it

  • The links are within #content?

  • Yes, those outside, the load does not work.

1 answer

2


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

There are two simple ways to solve this problem:

  • Put your routine into a separate function and re-link the event with content.on("click", suaRotina);

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

  • Thanks a lot man, it worked!! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.