views:

52

answers:

2

After getting a new page with $.get none of the javascript will run on the new page.

Is there a way to make javascript use the new page too?

Many thanks

  • Dorjan

Edit: Example:

$(function() {
    $('.viewPage').click(function() {
     $('#mainarticle').fadeOut('slow')
     $.get($(this).attr('href'), { js: "1" }, function(data) {
      $('#mainarticle').html(data).fadeIn('slow');
     });
     return false;
    });
});

Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).

I hope that clarify's the issue.

A: 

Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.

Noon Silk
Hmm... I'll have a look. Just to make sure we're on the same page the jQuery waits on an anchor tag click. But on the new version of the same page (lets say a ajax reload) all the anchors are ignored.I've been unsuccessful finding the right function but am reading between checking here.
Dorjan
I just found jQuery.getScript( url, [callback] ) which I think is what you meant, but wasn't what I meant. I'll clarfy the question.Thanks though!
Dorjan
+2  A: 

You need to bind events to your anchors using live:

$('a.something').live("click",function() {
    alert('this will still work after a.something has been replaced via ajax');
});

Another way using $.get's callback:

$.get( "page.html", function(data) {
    $('#someDiv').html(data);
    $('a.something').click(function() {
        alert('this will still work after a.something has been replaced via ajax');
    });
});

Now that I've seen your code:

$(function() { 
    $('.viewPage').live("click",(function() { 
        $('#mainarticle').fadeOut('slow') 
        $.get($(this).attr('href'), { js: "1" }, function(data) { 
            $('#mainarticle').html(data).fadeIn('slow');
        }); 
        return false; 
    }); 
});
karim79
Just testing now, looks like this is the right one though!
Dorjan
Perfect! I had to upgrade my jQuery (I was using 1.2.2 which is why I didn't find this!)Fantasy, thanks Karim.
Dorjan
I actually did it before I saw your update (since I had to download the new jQuery, your first instructions was perfect my friend :) )
Dorjan
(I would've given you a vote up but I can't yet, too new it tells me!)
Dorjan
@Dorjan - oops, I should have mentioned that you need jQuery 1.3
karim79
Luckily I read the API eh? :)
Dorjan