the jQuery 'on' function is supposed to catch events for elements created in the future but in my code it doesn't seem to work unless the item has already been created. Here is the code that fails:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#div1').on('click', function(e) {
$('#div2').html('<div id="div3">Now Click Me!</div>');
});
$('#div3').on('click', function(e) { alert('OLA!'); });
});
</script>
</head>
<body>
<div id='div1' style='border:black 1px solid; background:yellow'>CLICK ME</div>
<div id='div2' />
</body>
</html>
Clicking 'div2' creates 'div3', but then clicking on 'div3' does nothing. On the other hand, if I change the javascript code to look like this:
$(function () {
$('#div1').on('click', function(e) {
$('#div2').html('<div id="div3">Now Click Me!</div>');
$('#div3').on('click', function(e) { alert('OLA!'); });
});
});
it works, but it works because the event handler for 'div3' is no being declared AFTER the div3 element has been added. Perhaps I am misunderstanding how 'on' is supposed to work?
Try this...
$('body').on('click', '#div3', function(e) { alert('OLA!'); });
The first selector needs to be a common ancestor element that the events will bubble to.
You should delegate the event from one of static parents of the element or document object:
$('#div2').on('click', '#div3', function(e) {
alert('OLA!');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With