Reputation: 1926
This simple jQuery will not work for me when using on
. Is there another method to use on
? Will on
not work with a class
. I'm using jQuery JavaScript Library v1.8.3
I'm trying to move some old code from live()
to on()
.
$(".subUser").on("click",function() {
alert("The paragraph was clicked.");
});
<div class="container">
<div><i class="icon-add subUser"></i></div>
</div>
Upvotes: 0
Views: 55
Reputation: 10906
check this how you should replace your code
// Bind
$( "#members li a" ).on( "click", function( e ) {} );
$( "#members li a" ).bind( "click", function( e ) {} );
// Live
$( document ).on( "click", "#members li a", function( e ) {} );
$( "#members li a" ).live( "click", function( e ) {} );
// Delegate
$( "#members" ).on( "click", "li a", function( e ) {} );
$( "#members" ).delegate( "li a", "click", function( e ) {} );
REFERENCE
http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html
Upvotes: 0
Reputation: 148150
Your code seems alright if you do not add elements with class subUser
dynamically. You probably need to put in document.ready
$(document).ready(function(){
$(".subUser").on("click",function() {
alert("The paragraph was clicked.");
});
});
If you are adding elements dynamically then you need event delegation. You have to use the parent element in selector which is present at the time your bind code gets executed or you can use document or body.
$(document).ready(function(){
$(document).on("click", ".subUser", function() {
alert("The paragraph was clicked.");
});
});
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, Reference.
Upvotes: 2
Reputation: 74738
You can change to this then:
$(".container").on("click", ".subUser" ,function() {
As you are moved your code from .live()
to .on()
then you have to delegate the event to the static parent which was available before the dom change.
so in your case it seems that .container
class was available at that point of time then you have to delegate to that or you can delegate to $(document)
directly because document always available to delegate the event(this might be little slower
).
Upvotes: 0