Search code examples
javascriptandroidtouchstart

Touchstart event not Working on originally hidden button


I am creating an Android app and have 2 buttons. 1 start and 1 stop. To start with the stop button is visible once the start button has been clicked then the stop button becomes visible and start invisible.

I am trying to get a touchstart event on the STOP button (would liek to add to start button as well but not as essential). However, for some reason my below code is not working properly. Could some please let me know what i have missed out.

Background: - using jquery to hide my buttons - the buttons with background image

JAVASCRIPT:

var b=document.getElementById('STOP'),start=0;

//Check for touchstart
if('ontouchstart' in document.documentElement) 
{
    document.getElementById("notouchstart").style.display = "none";
}

//Add a listener that fires at the beginning of each interaction
[b].forEach(function(el){el.addEventListener('touchstart',interact);});

//Add the event handlers for each button
b.addEventListener('touchstart',highlight);

//Functions Store the time when the user initiated an action
function interact(e) 
{
    start = new Date();
}

//Highlight what the user selected and calculate how long it took the action to occur
function highlight(e) 
{
    e.preventDefault();
    e.currentTarget.className="active";
    if(start)
    {
        alert("test")
    }
    start = null;
}

HTML BUTTON:

<INPUT TYPE="button" style="background:url(images/Start_Btn.png); background-color:transparent; width:150px; height:186px; border:none; cursor:pointer;" id="START" onClick="startBTN();">
<INPUT TYPE="button" style="background:url(images/Stop_Btn.png); background-color:transparent; width:150px; height:186px; border:none; cursor:pointer;" id="STOP">

Solution

  • I have solved my issue, I was trying to get too clever about it. I simply need 2 lines of code within the onload function:

        function onload()
        {
        /* PART 1 - sets touch even to button
           PART 2 - Defines what JavaScript function to run
           PART 3 - Indicates to set the touch event to false on first load */
            document.getElementById('START').addEventListener('touchstart', startBTN, false);
            document.getElementById('STOP').addEventListener('touchstart', stop, false);
        }
    

    To Call Function onload:

    <body  onload="onload();">
         //HTML CONTENT
    </body>
    

    Hope this helps someone