Wednesday, April 6, 2011

How can I bind events to the appended element?

I tried to show an error message using the jquery effect fadeTo and tried to hide the message by appending a button and using fadeout but doesn't seem to work.

What I did was:

$("#sub_error")
  .fadeTo(200, 0.1, function()
  {
    $("#sub_error")
      .html(error.join("<br/><br/>"))
      .append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">')
      .addClass('subboxerror')
      .fadeTo(900,1);
  });

$("#err_ok").click(function() 
{
  $("#sub_error").fadeOut("slow");
});

What am I doing wrong, could someone help me?

From stackoverflow
  • the #err_ok element doesn't exist at first so the .click() handler is not applied to it.

    You can solve this by putting

    $("#err_ok").click(function () {
      $("#sub_error").fadeOut("slow");
    });
    

    in a function and call the function after creating the element in the DOM.

    Edit: This should be a full solution:

    $("#sub_error").fadeTo(200, 0.1, function() {
        $("#sub_error")
          .html(error.join("<br/><br/>"))
          .append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">')
          .addClass('subboxerror')
          .fadeTo(900, 1);
        bindEvents();
    });
    
    function bindEvents() {
        $("#err_ok").click(function() {
            $("#sub_error").fadeOut("slow");
        });
    }
    

    There is also a "live" function that binds events to future created DOM elements too.

    Shog9 : You could also just bind the event to err_ok in the function where it is created.
    jarus : thanks a lot Thomas , it worked , i was suspecting may be it is not accessing the appended button ... thank you ;)
    Thomas Stock : No problem. I had the same problem before, took me a while to figure out :-)
  • FWIW, there are filed tickets about fadeTo/fadeOut bugs on the JQuery bug tracker.

  • There are a couple of ways to do this. One, you can append the click handler to the element after it is inserted:

    $("#sub_error").fadeTo(200, 0.1, function() {
        $("#sub_error")
          .html(error.join("<br/><br/>"))
          .append('<br/><input type="button" name="err_ok" id="err_ok" value="ok">')
          .addClass('subboxerror')
          .fadeTo(900, 1)
          .find('#err_ok')
          .click( function() {
            $("#sub_error").fadeOut("slow");
          });
    });
    

    Or two, you can use the live event handler so that any element with the "err_ok" id will get the click handler whenever it's created.

    $('#err_ok').live('click', function() {
        $('#sub_error').fadeOut('slow');
    });
    

0 comments:

Post a Comment