-1

I use bootstrap and a clock picker from http://weareoutman.github.io/clockpicker/

It works fine when I load the main page. But when I load new content from another php file into a div using AJAX call, clockpicker stops working.

Clockpicker use jQuery at the bottom of the page.

The new content which I load with ajax contains the clockpicker button as well. But it won't work. Is there something wrong with the jQuery at the bottom of the page maybe?

I'm new on jQuery and don't know the syntax nor the language.

<?PHP

echo "<div class=\"input-group clockpicker col-md-6\" data-placement=\"right\" data-align=\"top\" data-autoclose=\"true\">";
  echo "<input 
    type=\"text\" 
    class=\"form-control input-sm\" onchange=\"ajax_function('kuk','alter_schedule.php?ltime='+this.value+'&cid=".$child_id."&date=".$row['date']."&what=3')\" value=\"".date("H:i", strtotime($row['schedule_start']))."\">";
  echo "<span class=\"input-group-addon\">";
    echo "<span class=\"glyphicon glyphicon-time\"></span>";
  echo "</span>";
echo "</div>";

?>

<script type="text/javascript">

$('.clockpicker').clockpicker();

</script>
Rob Baillie
  • 3,436
  • 2
  • 20
  • 34

1 Answers1

5

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 2
    Many people delegate from the document, but even the documentation says you shouldn't => *For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.* ... delegate from the earliest ancestor you can. – PlantTheIdea Dec 17 '14 at 13:35
  • Although correct, in this case manually binding in the `success` function is probably the only option; it doesn't seem to support event delegation. – jeroen Dec 17 '14 at 13:43
  • 1
    I was just looking through the docs so that I could be more specific for the plugin @jeroen and I think you're right. – Jay Blanchard Dec 17 '14 at 13:47
  • Thanks for the respond. As i wrote earlier I'm new to jQuery and don't know the syntax. But i tried do add (document).on in the beginning of the jQuery at the bottom of the page. But that didn't helped me. I really appreciate the help and maybe @JayBlanchard can show me how the syntax? Thanks a lot :) – user1435012 Dec 17 '14 at 14:15