February 27, 2013

jQuery On() is not working for $(document)

Question by Jason Biondo

I am currently in the process of integrating the dropkick.js plugin into my app, but I have run into a few snags. When I change backbone views the events do not work properly and the .live() event associated in dropkick.js just flat out doesn’t work at all. Nothing fires. I decided to upgrade this to using the .on() function and got it sort of working (even though it still deletes my url for some reason).

This doesn’t work at all:

$(document).on("click", ".dk_toggle", function() {

This only works somewhat:

$(".content").on("click", ".dk_toggle", function() {

Do you know why document doesn’t work at all?

My backbone $el is $(".content").

Answer by Starx

Instead of document, use body. It basically gives the same behavior.

$('body').on("click", ".dk_toggle", function() {
//....
});
...

Please fill the form - I will response as fast as I can!