Does anyone know why in my code "delegate" function works but not "on" or "bind"?
$(document).ready(function(){
$("div").on("p","click",function(){
$("p").css("background-color","pink");
});
});
Thanks
What you're currently using is applicable for .delegate() . The correct parameters order for .on() is:
.on( events [, selector ] [, data ], handler(eventObject) )
so you need to specify the event first then follow by your selector:
$("div").on("click","p",function(){
$("p").css("background-color","pink");
});
Try
$(document).ready(function(){
$("div").on("click","p",function(){
$(this).css("background-color","pink"); // this will change color on inside p
});
});
$(document).ready(function(){
$("div").on("click","p",function(){
$('p').css("background-color","pink"); // this will change color on all p
});
});
"As of jQuery 1.7, .delegate()
has been superseded by the .on()
method."
"As of jQuery 1.7, the .on()
method provides all functionality required for attaching event handlers."
Using the .bind()
method is very costly as it attaches the same
event handler to every item matched in your selector.
You should stop using the .live()
method as it is deprecated and has
a lot of problems with it.
The .delegate()
method gives a lot of "bang for your buck" when
dealing with performance and reacting to dynamically added elements.
That the new .on() method is mostly syntax sugar that can mimic
.bind()
, .live()
, or .delegate()
depending on how you call it.
The new direction is to use the new .on
method. Get familiar with
the syntax and start using it on all your jQuery 1.7+ projects.
Event type
must be first parameter in .on()
statement
selector
must be second parameter.
data
must be third parameter and its optional
Instead of
$("div").on("p","click",function(){
$("p").css("background-color","pink");
});
use
$("div").on("click","p",function(){
$("p").css("background-color","pink");
});
Instead of using $('div').on('click','p',function...
use $('div p').on('click',function...
$(document).ready(function(){
$("div p").on("click",function(){
$(this).css("background-color","pink");
});
});