HTML:
<div class='cf' id='content'>
<div id='leftColumn'>
</div>
<div class='microposts'>
<div class="micropostContent">
</div
</div>
<div id='rightColumn'>
</div>
</div>
Prepend:
$('.micropostContent').prepend('<%= j render("users/partials/micropost") %>');
Some of the functions:
$(".micropost_content").focus(function() {
this.rows = 7;
var micropostBox = $(this),
xButton = $(this).parent().find(".xButton");
micropostBox.hide().addClass("micropost_content_expanded").show().autoResize();
xButton.css("display", "block");
xButton.click(function() {
micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
micropostBox.val("");
xButton.hide();
});
});
$(".comment_box").focus(function() {
this.rows = 7;
var $commentBox = $(this),
$form = $(this).parent(),
$cancelButton = $form.children(".commentButtons").children(".cancelButton");
$(this).removeClass("comment_box").addClass("comment_box_focused").autoResize();
$form.children(".commentButtons").addClass("displayButtons");
$form.children(".commentButtons").children(".cancelButton");
$cancelButton.click(function() {
$commentBox.removeClass("comment_box_focused").addClass("comment_box");
$form.children(".commentButtons").removeClass("displayButtons");
$commentBox.val("");
});
});
$('.micropostOptions').on('click',function(){
var postMenu = $(this).find('.postMenu');
if(postMenu.is(':hidden') ){
$('.postMenu').hide();
$('.micropostOptions').removeClass("postMenuHoverState");
postMenu.show();
$(this).hide().addClass('postMenuHoverState').show(60);
}else{
postMenu.hide();
$(this).removeClass("postMenuHoverState");
}
});
The functions that stop working are focus and click functions. They only work again after refreshing until I post another ajax message/micropost.
The .comment_box function doesn’t work on the message that’s been prepended but it works on all the previous messages. The .micropostOptions function doesn’t work all. Then after refreshing everything works just fine.
Am I missing something?
Kind regards
Because the events are only bound to existing items when you declare them.. declare using on and attach to a parent element instead
The closer the parent is to the element you are attaching functionality to the better, for example the parent container “.cf” or “.microposts” instead of document in your case.
To elaborate, in your example, you are only binding events to the individual elements, and when new items are added, they don’t have the same event bindings… When you bind the event to a higher level element, then you are basically saying “apply this handler to everything inside of this parent element that matches this selector”.