I have a div with class name profile-activity-box which comes as a AJAX response (html code). The AJAX part works perfectly, so no problem there. With ‘works’ I mean that the div is displayed correctly. Now when I put a click event on it, it doesn’t work. I can’t figure out what goes wrong. This is the code:
<div class="row-fluid main-div">
<h3 class="offset1">Laatste activiteit</h3>
<div class="span8 offset1" id="activity-box-wrapper"></div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var id = <?php echo $user['User']['id']?>;
console.log(id);
$.ajax({
type: "POST",
cache: false,
url: '/users/getCheckins',
data: "id="+id,
success: function(resp) {
//console.log(resp);
$('#activity-box-wrapper').html(resp);
},
error: function(e) {
console.log("Server said (error):\n '" + e + "'");
}
});
// this works! So the element is defined!
console.log($('.profile-activity-box'));
// but this does not !
$('.profile-activity-box').on('click',function(){
$(this).next().slideToggle(100);
console.log("hello!");
});
});
</script>
This is the AJAX response before someone asks me to post it:
echo "<div class='profile-activity-box'>";
echo "<div class='span6'>";
echo "<img src='/img/gf80x80.jpg' alt='' />";
echo $value['Game']['title'];
echo "</div>";
echo "<div class='span3 offset3' style='padding: 30px;'> ";
echo "<img src='/img/thumbsup.png' alt='likes' />";
echo "<span class='like-count'> 2 </span>";
echo "<img src='/img/messagebubble.png' alt='comments'".
"style='padding-left:30px' />";
echo "<span class='comment-count'> 4</span>";
echo "</div>";
echo "</div>";
echo "<textarea style='display:none;' class='profile-comment-box' rows='3'".
"placeholder='plaats een comment :)'></textarea>";
Once again, this whole thing is displayed correctly and is also defined at the time I use the click event. What am I doing wrong here? Thanks.
You can only add handlers to elements already available.
But your
.profile-activity-boxis not there before ajax response.To overcome, this situation, we use jQuery on.
We apply handler to already present parent element (
#activity-box-wrapperin this case) and when we click at parent, we check if that was on.profile-activity-boxtoo.