I recently asked a question about triggering dynamically created divs, and was introduced to the .on() function.
'keyup' works great, 'mouseover' works, a few others I've tested work but 'click' just will not fire.
I created added information to a div via ajax and .php which holds some data like this:
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html);
}
});
}
I wanted to trigger on keyup for an element within that created div and this code works for that:
$("#notebox").on('keyup', '.note-field', function(event){
var thisString = $(this).val();
$keyLength = thisString.length;
$rowCount = Math.ceil($keyLength/40);
$currentRow = $(this).attr("rows");
if($currentRow < $rowCount){
$(this).animate({rows:$rowCount},50);
}
});
This code however does NOT work:
$("#notebox").on('click', '.note-field', function() {
alert("clicked");
});
You can just use click like this:
$("#notebox").click( function() {
alert("clicked");
});
dynamic DOM and jQuery is a pain. I know its deprecated but I have used in the past with great results: http://api.jquery.com/live/
FWIW - you could also try using bind() - http://api.jquery.com/bind/
I had an .stopPropagation(); somewhere else in the code in the encompassing div, I commented it out for now and it works, thanks.
Is it possible to attach click event after html is appended.
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html).bind('click', function() { /* Click event code here */ }); // id divID is #notebox
}
});
}