Reputation: 1873
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?
Upvotes: 0
Views: 168
Reputation: 532455
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');
});
Upvotes: 0
Reputation: 11266
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.
Upvotes: 2
Reputation: 26227
FWIW, there are filed tickets about fadeTo/fadeOut bugs on the JQuery bug tracker.
Upvotes: 0