Hire Me

Solved - jQuery Mobile Click Event Not Firing After AJAX Page Request Completes

How to make sure jQuery events stay bound to their controls when refreshing elements of a page via an AJAX call

Posted on Friday, September 4, 2015 at 10:37 PM into jquery javascript code by Steve Woods

Today I had a weird problem that, like most software issues, made complete sense once I'd figured it out, but almost cost me my remaining hair while I was trying to get to the bottom of it.

Basically I have an application which has a button that causes a menu to slide out from the right hand side of the page, a mobile menu, as featured on many websites.

In this particular case though, the pages are handled by the jQuery Mobile framework - this is a set of Javascript libraries that give you some cool effects like touch buttons, dropdown menus and page transitions - all of which are nice to have on a mobile device because they improve the "feel" of the app.

The page transitions are handled via an Ajax call which displays a loading icon, then a cool "slide" effect to the new page when a link is clicked - all good.

Originally I was attaching an event to my "menu toggle" button using code like this:

$(document).ready(function() {
    $('.toggler').click(function() { // slide out the menu });

Pretty standard really and it worked well - until I clicked a link and went to a new page. The click event did not get re-attached to the button so obviously it did nothing - not good!

The reason for this is because during the page refresh, the button was reinitialised - but because the page did not specifically reload, the $.ready() event didn't get fired, which meant my button didn't get an event reattached to it.

The workaround was to BIND the event to any object under a parent (in this case the document) so that whenever the parent object was refreshed, the event would remain bound.. and it's as simple as this:

$(document).on('click','.toggler', function() { 
     // Slide the menu

Happy days! I hope this helps and saves you some time :)



Please consider what you post!
Chillax if you're angry.