Ok, why in gods name can’t I figure this out!

Adding simple elements to the DOM works…no problem.

   1:  new_elem = '<a href="#" onclick="alert('alert')">MyAdd</a>';
   2:  var test = $(new_elem);
   3:  $('#home_column').prepend(test);

I end up with a link…when I click it…I get an alert.

BUT!….when I have the same code in the success of an ajax call the elements are added to the DOM but nothing happens when I click on it!…I know! Crazy right?

 

   1:  $.ajax({
   2:          success: function(data){
   3:              new_elem = '<a href="#" onclick="alert('alert')">MyAdd</a>';
   4:              var test = $(new_elem);
   5:              $('#home_column').prepend(test);
   6:          }, 
   7:          url: 'http://twitter.com/statuses/friends_timeline.json' + app.twitter.since_parameter()
   8:      });
 

So….this code is placed in $(document).ready….it runs…the element is added to the DOM…life is good right? NOPE! I can’t click on it…well I can but nothing happens.

 
I think my ajaxSetup is pretty standard...
 
   1:  $.ajaxSetup({
   2:      mode:'queue',
   3:      beforeSend: function(xhr) {
   4:          var auth = $.base64Encode(USERNAME + ":" + PASSWORD);
   5:          xhr.setRequestHeader("Authorization", "Basic " + auth);
   6:          xhr.setRequestHeader("Cookie", "");
   7:          xhr.setRequestHeader("If-Modified-Since", 'Sun, 1 Jan 2007 18:54:41 GMT');
   8:      },
   9:      dataType: "json",
  10:      type: "GET"
  11:  });
 
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

  2 Responses to “jQuery, Ajax, prepend and events (onclick?)”

  1. delegation is how I coded around the “issue” but I don’t yet understand why a programmatic added element would work just fine but a programmatic added after ajax element would not work…shouldn’t the results be consistent?

  2. http://docs.jquery.com/Release:jQuery_1.3

    Live Events

    jQuery now supports “live events” – events that can be bound to all current – and future – elements. Using event delegation, and a seamless jQuery-style API, the result is both easy to use and very fast.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

   
© 2012 eric.polerecky.com Suffusion theme by Sayontan Sinha