0

I have the following javascript code:

$(document).ready (function()
{ 
    setInterval("RepeatedlyCallUpdate()",10000);
    // Other code
    $('#btnRefresh').click(function(e){
        e.preventDefault();
        alert ("Test");
    }); 
    // Other code

}); 

function RepeatedlyCallUpdate() { 
  $.ajax({
   url: "/getdled.php",
   data: "user=success",
   success: function(msg){
     console.log(msg);
     var oldhtml=$("#Downloaded").html();
     if ( msg !== oldhtml ) {
        $("#Downloaded").html(msg);
     }       

   }
 });
}

The html code for #Downloaded:

<div id="Downloaded"><h3 style="padding-left:20px;">Downloaded files</h3>
</div>

At runtime, the #Downloaded div block is populated with html code so that it becomes this:

<div id="Downloaded"><h3 style="padding-left:20px;">Downloaded files</h3>
<ul class="nav nav-pills">
<li>
<button style="margin-left: 15px;" class="btn btn-primary refreshbtn" type="button" id="btnRefresh">
Refresh
</button>
</li>
</ul><div>
<div class="row">
    <div style="margin-left: 15px;" class="col-md-4">
    <a href="somthing">Some link</a></div>
    <div class="col-md-1">314M</div>
    </div>
</div>
</div>

The issue is that my #Downloaded button click event does not fire. What am I missing?

Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86
  • Because you're trying to register the listener before the element ever exists. – Evan Trimboli Jul 24 '15 at 02:30
  • possible duplicate of [Direct vs. Delegated - jQuery .on()](http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on) – Phil Jul 24 '15 at 03:28

1 Answers1

0

You can use event delegation

$("#Downloaded").on('click', '#btnRefresh', function(){
    alert("lol");
});
Phil
  • 157,677
  • 23
  • 242
  • 245
Vemba
  • 40
  • 3