Bozzzi
Bozzzi

Reputation: 133

Overriding the Back Button in PhoneGap Android

I`m trying to accomplish more than one addEventListener, but something is wrong?

For example if we have 3 divs on page and first one is displayed on the beginning and other two hidden.

<div id="d1">
<a onClick="
document.addEventListener("backbutton", show_div1, false); 
$('#d1').hide();  
$('#d2').show(); 
"
</a>
</div>

<div id="d2"></div> - initially hidden
<div id="d3"></div> - initially hidden

It shows div 2, hides div 1 and sets listener for back button to show_div1(), and everything works OK. On back key pressed it alerts "I should show #div1", as it should (//$('#d1').show(); is comented)

show_div1(){
//$('#d1').show(); $('#d2').hide(); 
alert ('I should show #div1');
}

But now comes the problem

<div id="d2">
<a onClick="
document.removeEventListener("backbutton", show_div1, false);
document.addEventListener("backbutton", show_div2, false); 
$('#d2').hide();  
$('#d3').show(); 
"
</a>
</div>

It immediately fires "I should show #div2" even back button is not pressed! addEventListener like started main function show_div2() and not just set listener on back button to that function.

show_div2(){
//$('#d2').show(); $('#d3').hide();
alert ('I should show #div2');
}

What could be the possible reason for this happening?

Upvotes: 2

Views: 2792

Answers (1)

Omar Kam
Omar Kam

Reputation: 111

try this, on device ready add a listener for backbutton like this

var onBackButton = function(){show_div2();}; //the initial state
document.addEventListener("backbutton", onBackButton, false); 

And

don't use onClick with phoneGap

use href, or ontouchend and be sure that your < a > is visible because you dont have anything inside(display block in your css file)

<div id="d1">
    <a href='javascript:onDivClick(1)' style='display:block; width:100%; height:100%;'></a>
    // <a ontouchend='onDivClick(1)'></a> will be better
</div>
<div id="d2">
    <a href='javascript:onDivClick(2)' style='display:block; width:100%; height:100%;'></a>
</div>

in javascript

function onDivClick(var case)
{
    switch(case)
    case 1:
        $('#d1').hide();  
        $('#d2').show();
        onBackButton = function(){show_div1();};
    break;
    case 2:
        $('#d2').hide();  
        $('#d1').show();
        onBackButton = function(){show_div2();};
    break;
}

Upvotes: 2

Related Questions