Skip to content

Instantly share code, notes, and snippets.

@macdonst
Created May 4, 2011 16:14
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save macdonst/955496 to your computer and use it in GitHub Desktop.
Save macdonst/955496 to your computer and use it in GitHub Desktop.
PhoneGap Android Back Button Example
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>PhoneGap Back Button Example</title>
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.5.js"></script>
<script type="text/javascript" charset="utf-8">
// Call onDeviceReady when PhoneGap is loaded.
//
// At this point, the document has loaded but phonegap.js has not.
// When PhoneGap is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
console.log("I've been loaded");
document.addEventListener("deviceready", onDeviceReady, false);
}
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
}
/**
* Global Variables
*/
var cur = null;
// Back key event handler
//
function onBackKey() {
console.log("I've caught a back key");
// We are going back to home so remove the event listener
// so the default back key behaviour will take over
document.removeEventListener("backbutton", onBackKey, false);
// Hide the current dive and show home
document.getElementById(cur).style.display = 'none';
document.getElementById('home').style.display = 'block';
cur = 'home';
}
function goToDiv(id) {
// We are moving to a new div so over ride the back button
// so when a users presses back it will show the home div
document.addEventListener("backbutton", onBackKey, false);
// Hide home and show the new div
document.getElementById('home').style.display = 'none';
document.getElementById(id).style.display = 'block';
cur = id;
}
</script>
</head>
<body onload="onLoad()">
<div id="home">
Back Button Home<br/>
<a href="javascript:goToDiv('div1')">Div One</a><br/>
<a href="javascript:goToDiv('div2')">Div Two</a>
</div>
<div id="div1" style="display: none">
Div One
</div>
<div id="div2" style="display: none">
Div Two
</div>
</body>
</html>
@davidsyw
Copy link

Great. Thanks for your answer and reference link.

@thachnuida
Copy link

Hi macdonst, thanks for your example.But I got a problem here, when run in emulator I can hide an element after push on Backbutton, but when I try on real device, the element wasn't hide after touching on screen.

My device is Lenovo P700i, android 4.0. Do you know what was the reason of this problem?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment