Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery "on" isn't catching events

Tags:

jquery

events

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?

like image 759
LineloDude Avatar asked Dec 06 '25 04:12

LineloDude


2 Answers

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.

like image 170
alex Avatar answered Dec 08 '25 17:12

alex


You should delegate the event from one of static parents of the element or document object:

$('#div2').on('click', '#div3', function(e) {
     alert('OLA!'); 
});
like image 33
undefined Avatar answered Dec 08 '25 16:12

undefined