1

I have this function:

$(document).on('scroll', function(e)
{
  if (processing)
     return false;

  if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.9)
  {
     processing = true;

     var resource = $('#lazyLoad').attr('href');

     $.get(resource, '', function(data)
     {
        $('#lazyLoad').remove();

        $('#content').append(data);

        step++;
        processing = false;
     });
  }
});

I add some html code to my page every time this function is called. But other Javascript functions are not triggered when I click on a newly added html button. So I guess the DOM-element was not porper updated. But how do I proper update the DOM-element?

My Handler looks like this:

$('.article_action.un_read').on('click', function(event)
{
  event.preventDefault();

  var resource = $(this).attr('href');
  var elElemente = $(this);

  $.get(resource, '', function(data)
  {
     var obj = $.parseJSON(data);

     if(obj.status == 1)
        elElemente.html('📕');
     else
        elElemente.html('📖');
  });
});

So it also uses the on function.

Pascal
  • 2,175
  • 4
  • 39
  • 57
  • 1
    check: http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre – halilb Jun 20 '13 at 07:09
  • thanks halilb, that thread was exactly the thing I was looking for. – Pascal Jun 20 '13 at 07:26

3 Answers3

4

Try it like this :

$('#content').on('click', '.article_action.un_read', function(event) {
    event.preventDefault();

    var resource = $(this).attr('href');
    var elElemente = $(this);

    $.getJSON(resource, '', function(obj) {
        elElemente.html(obj.status == 1 ? '📕' : '📖');
    });
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You have to bind the button clicks with delegate-events.

$('#parentElement').on('click', 'button', function () {});
Ilu
  • 894
  • 6
  • 12
0

you need to mention the event binder declaration

$(<selector>).on('click', <handler>);

again inside the function which appends the html.

check the sample fiddle

edit: but first you should unbind old events inside the function which appends the html to prevent callback from multiple call.

$(<selector>).off();
Pank
  • 13,800
  • 10
  • 32
  • 45
scarecrow
  • 6,624
  • 5
  • 20
  • 39