0

again. Well,I'm doing also pushState script i was doing it with jquery 1.6.2 but it was working with .live() but with v2.0.3 of jquery it's deprecated. So, I don't know how can I replace it, look:

$('.a').live('click', function(e){
        history.pushState(null, null, this.href);
        replacePag(this.href);
        e.preventDefault();
        $(window).bind('popstate', function(){
        replacePag(location.pathname);
    });
    });

When i run it with one element with class .a it works fine, but my page has many .a elements. I tried it with .on() but neither it doesn't works.

$('.a').on('click', function(e){
            history.pushState(null, null, this.href);
            replacePag(this.href);
            e.preventDefault();
            $(window).bind('popstate', function(){
            replacePag(location.pathname);
        });
        });

If you can help me, Thanks for your help.

Well, my script is:

$(function(){
    var replacePag = function(ur) {
        $.ajax({
            url: ur,
            type: 'get',
            dataType: 'html',
            success: function(dat){
                var domm = $(dat);
                var titl = domm.filter('title').text();
                var htm = domm.filter('#body').html();
                $("#body").fadeOut(100,
                function(){
                    $(this).html(htm);
                    $('title').text(titl);
                    }).fadeIn( 1000 );
            }
        });
    }

    $('.a').live('click', function(e){
        history.pushState(null, null, this.href);
        replacePag(this.href);
        e.preventDefault();
        $(window).bind('popstate', function(){
        replacePag(location.pathname);
    });
    });
});
Darkness
  • 101
  • 1
  • 13
  • Also, you can't just replace `.live` with `.on` word for word, you have to target a currently existing element. Check zeh docs! – tymeJV Oct 03 '13 at 19:29

2 Answers2

1

Like this:

$(document).on('click', '.a', function(e){
    history.pushState(null, null, this.href);
    replacePag(this.href);
    e.preventDefault();
    $(window).bind('popstate', function(){
        replacePag(location.pathname);
    });
});

you need to bind to document to pick up the new elements as they're added.

Hope this helps.

Kyle Muir
  • 3,875
  • 2
  • 22
  • 27
1

The on function allows you to get round this by handling them on another element when the event "bubbles up to" a parent element. In this instance, we could say the document element – there may be a more specific common parent you could choose.

try this:

$(document).on('click','.a', function(e){
    history.pushState(null, null, this.href);
    replacePag(this.href);
    e.preventDefault();
    $(window).bind('popstate', function(){
        replacePag(location.pathname);
    });
 });
Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171