I have a question regarding jQuery’s live() function.
I am programming a forum. As soon as someone posts something and hits enter, jQuery appends the other posts and also inserts a textarea for comments, to which the following event handler applies:
//Comment on a post
$('.commenttext').keyup(function(e) {
if (((e.keyCode || e.which) == 13) && !event.shiftKey) {
comment($(this));
}
});
The function to post a comment is then called – well at least it should be. For the old posts it works fine, but not for the one that was just posted and appended.
I know that it is possible to preserve functionality using the live() function. However, as you can see, the post gets submitted when hitting enter, there is no button involved. So I wonder how to combine these things, i.e. using live() but without click: ?
FYI, the function to post something looks like this:
//Function to post
function post()
{
//Get posttext and preserve line breaks
var posttext=$('#posttext').val();
//Ajax if posttext is not empty
if(posttext!="")
{
$.ajax({
//blablabla
success: function(postid){
//Prepend posts with the new post
var newpost=posttext+'<br/><textarea id="commenttext'+postid+'" class="commenttext" placeholder=" Comment..."></textarea>';
$(newpost).hide().prependTo('#postsDiv').fadeIn('slow');
}
});
}
}
UPDATE 1:
I have changed the event handler to post something to this, which posts fine, but still the functionality is not there:
//Post something
$('#postDiv').on('keyup', '#posttext', function(e) {
if ((e.which == 13) && !event.shiftKey) {
post($(this));
}
});
UPDATE 2:
It works for now 🙂 I didn’t know both comment() and post() have to be live.
I now have the following two functions:
//Post something
$('#postDiv').on('keyup', '#posttext', function(e) {
if ((e.which == 13) && !event.shiftKey) {
post($(this));
}
});
and
//Comment on a post
$('.commenttext').live('keyup', function(e) {
if (e.which == 13 && !event.shiftKey) {
comment($(this));
}
});
It works fine, but it would be better to also use on() to comment. I have tried this:
$('.commentsDiv').on('keyup', '.commenttext', function(e) {
if ((e.which == 13) && !event.shiftKey) {
post($(this));
}
});
but it doesn’t work – how come? commentsDiv is the parent element of commenttext, which is the comment textarea. Do I need to address it with an id?
Thanks 🙂
.livecan be used with any event you want, not justclick(even custom events).NOTE: If you are using jQuery 1.7+, you should no longer use
.live, you should use.oninstead.Instead of
document, you should use the closest parent (this element needs to not be removed from the DOM though, if it’s removed, the events are removed too).P.S.
e.whichis normalized in jQuery, meaning it doese.keyCode || e.whichfor you.Docs: http://api.jquery.com/category/events/event-object/