-1

I have some code to display/hide an input button depending on a condition:

settings = settingsManager.readSettings();
if (settings) {
   $("#settings-back-button").show();
} else {
   $("#settings-back-button").hide();
}

However, this does not prevent the user from pressing the devices back button. How can I do this?

settings = settingsManager.readSettings();
if (settings) {
   $("#settings-back-button").show();
   disableDeviceBackButton(); // How to implement this?
} else {
   $("#settings-back-button").hide();
   reEnableDeviceBackButton();  // How to implement this?
}
Chris Snow
  • 23,813
  • 35
  • 144
  • 309
  • duplicate, see here: http://stackoverflow.com/questions/18211984/how-to-control-back-button-event-in-jquery-mobile – sina72 Feb 24 '15 at 12:35
  • I've updated my question. The other question is asking how to control the back button, but this question is about toggling the back button. – Chris Snow Feb 24 '15 at 13:04

1 Answers1

1

I think this code should work:

<!DOCTYPE html>
    <html>
      <head>
        <title>Back Button Example</title>

        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    var backButtonDisabled = false;
    // Wait for device API libraries to load
    //
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
    }

    // device APIs are available
    //
    function onDeviceReady() {
        // Register the event listener
        document.addEventListener("backbutton", onBackKeyDown, false);
    }

    // Handle the back button
    //
    function onBackKeyDown(e) {

        if (backButtonDisabled) {
            e.preventDefault();
        } 
    }

    function disableDeviceBackButton() {
        backButtonDisabled = true;
    }

    function reEnableDeviceBackButton(){
        backButtonDisabled = false;
    }

</script>
  </head>
  <body onload="onLoad()">
  </body>
</html>

It might have some improvements like not using a global variable (backButtonDisabled), you can use sessionStorage instead, but the important part is the e.preventDefault(); the avoid the back button default behaviour when you don't want to go back.

jcesarmobile
  • 51,328
  • 11
  • 132
  • 176