Reputation: 17940
I have the following HTML structure,which is a handlebars.js template.:
<div class="row" id="{{serviceId}}">
<div class="favorites" isfavorite="{{isFavorite}}">
<img src="{{favImg}}" style="width:25px;">
</div>
<!-- end .favorites -->
<div class="service">
<p class="title">{{serviceName}}</p>
</div>
<div class="small serviceStat">
</div>
<div class="small metric">
</div>
<div class="performance"></div>
<div class="icon email">
<img src="../images/email.png" style="width:27px">
</div>
</div>
When i try to bind an event to the email class using the .on()
method it does not work:
$('.row').on('click','.email',function(){alert('clicked')});
//or like this:
$('.email').on('click',function(){alert('clicked')});
But if i bind it with live it works:
$('.email').live('click',function(){alert('clicked')});
any idea what might cause it?
Upvotes: 1
Views: 84
Reputation: 5939
The issue is you need to bind your delegate handler ABOVE [the location where your .row
elements are going to exist] in the DOM...
If you have:
<div id="item-container">
<!--divs with class row go in here -->
</div>
you need to do this:
$('#item-container').on('click', '.email', function() {alert('clicked'); });
The reason for this is instances of your template do not exist in the DOM at document ready...so you need to bind the event to an element that does exist...aka, the item-container
Upvotes: 2
Reputation: 5052
This code
$('.row').on('click','.email',function(){alert('clicked')});
//or like this:
$('.email').on('click',function(){alert('clicked')})
Needs to be within this:
$(document).ready(function(){
/* Code goes here */
});
I am guessing it isn't. (This is to ensure that events are bound after the DOM is ready).
Either that, or you are using an old version of jQuery. .on
was added in one of the more recent versions.
Upvotes: 1