-3

Click events for the child nodes the parent are not fired when html is append to the div but event is fired when content is static on document.ready. Is there something im doing wrong here?

$(document).ready(function(e) {
runAPISearch(); //Make httpRquest to movieDBAPi
$('.card').click(function(e) {
console.log("remove div"); //CLICK EVENT NOT FIRED
});

$('.cardImg').click(function(e) {
    console.log("clicked Img"); //not fired either.
});

});

functions

function parseData(data){
var i=0;
for (i = 0; i < data.length; i++){
    var template = $("#template").html();
    var prependTemplate = template.replace("{{cardId}}", i).replace("{{imgSrc}}", poster_path);
    console.log(prependTemplate);
    $(".container").prepend(prependTemplate);
    }
}//ParseData ends

HTML TEMPLATE

<script type="text/template" id="template">
<div id="{{cardId}}" class="card">
<img class="cardImg" src="{{imgSrc}}"> 
    </div>
</script>
<div class="container">

et moi
  • 127
  • 1
  • 1
  • 9

2 Answers2

3

Refer to the answer on this question: Click event doesn't work on dynamically generated elements

You will need to bind the event to a static element and delegate your dynamic element:

$('container').on('click','div.card',function(){
    //your function
});

Same for the other dynamic element

Community
  • 1
  • 1
CreMedian
  • 763
  • 5
  • 15
0

By the time the http response comes back your functions have already been called because your http request is asynchronous. Try using jquery on function like so.

$("body").on( "click", ".card", function() {
  console.log("remove div");
});

$("body").on( "click", ".cardImg", function() {
  console.log("clicked Img");
});
Timothy Radier
  • 323
  • 4
  • 15