Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event binding with .on()

Can someone explain to me why this works:

parentBox.on('click', '.close', function() {
   parentBox.fadeOut();                  
   return false; 
 });

But this does not:

var closeBox = $('.close');
parentBox.on('click', closeBox, function() {
   parentBox.fadeOut();
   return false; 
});

When caching '.close' into a var, no matter where I click in the parent element, it fades out as if the event handler was attached to parentBox rather than '.close'.

like image 363
JacobiOjera Avatar asked May 11 '26 03:05

JacobiOjera


1 Answers

This not works because

.on( events [, selector] [, data], handler(eventObject) )

second parameter is always selector (string type), if you need to bind to specific objects use

 closeBox.bind('click',function(){/* code here */})
like image 110
zb' Avatar answered May 13 '26 22:05

zb'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!