I’m working on a web app with JQuery Mobile 1.2 and php. From the profile page, I have a popup asking the user to confirm logout. What I want to do is intercept that button with a click event to process the logout via an ajax request.
I have a custom.js file included in all my project pages. The app loads in the accounts page. I know it is getting loaded and working across the ajax navigation.
When I include this code in custom.js:
$("#perfil").live('pageshow',function(event){
alert('This page was just enhanced by jQuery Mobile!');
});
I get the alert when the profile page is shown. The problem is the click function.
When I include this:
$("#perfil").live('pageshow',function(event){
alert('This page was just enhanced by jQuery Mobile!');
$('#logoutButton').click(function(){
$('#output').html('Logging Out...');
$.get("api/logout",function(data){
if(data.success) {
window.location = "index"
}
else{
$('#output').html('Logout failed. Try again');
}
}, "json");
});
});
The behavior is odd. When I navigate from the main page to the profile page, I get the alert. But the button doesn’t respond. However, when I refresh (or initially load the app from the profile page) the button behaves correctly and runs the the javascript logout function.
Here is the code for the html button:
<a id="logoutButton" data-role="button" data-icon="check"
data-inline="true" data-theme="e">Si, finalizar.</a>
Your custom.js on your profile page is not actaully getting loaded (more on that below), and as a result when you are binding the click event your button does not exist in the DOM, you can get around this by using event delegation for example
Now the reason why your custom.js isn’t getting loaded is because by default when you load a page in jQuery Mobile the default behavior is to load just the
data-role="page"div via ajax and attach it to the DOM of the current page. The important part to realize is that only the div page gets loaded, and not any other resources on that page.If you want a custom script on a seperate page to be loaded you need to include it within the div
data-role="page"wrapper. You can also tell JQM to fully load a page without ajax by using thedata-ajax="false"attribute on your links (orrel="external"if its a different domain).As a side point you should consider using .on instead of
.liveas of jQuery 1.7.livehas been depreciated.