Search code examples
javascriptjquerymobile-safariweb-developer-toolbar

JavaScript button no longers works on mobile


So I'm troubleshooting an issue in our app and can't figure it out. I haven't written the base code and can only inject CSS and Javascript. There's a very basic span element with an ID, below that is a snippet of Javascript basically saying "if element with ID submitButton is clicked, submit form #createForm". However, on mobile it's broken and the browser is not giving any errors.

<form method="post" action="page.html" id="createForm">
    <span id="submitButton">Submit form</span>
</form>
<script> 
    $("#submitButton").on("click", function (event) {
        if (attributeEqualsDisabled($(this).attr('disabled'))) {
            return true;
        }
        $("#submitButton").attr('disabled', true);
        $('#createForm').submit();
    });
</script>

Now, this works perfectly on desktop browsers, even when using the "display as iphone" mode Chrome has. You can click the button, everything works.

However on mobile safari and when adding the page as a webapp the button no longer works. When you press it the page just scrolls to the top and does nothing. I've checked it out through my Mac and everything seems normal and exactly the same as on desktop. I can even run $("#submitButton").click(); on my iphone through the console and it functions perfectly.

There are no errors or warnings in the console. Does anyone have any suggestions to troubleshoot this? I sadly can't give direct access to the code because everything is on an IP locked server.

Is there any way of seeing exactly what happens when I click the button? I've tried the "Timelines" tab but that shows nothing when I press the button.


Solution

  • This answer by another user fixed it: https://stackoverflow.com/a/3026621/3461722

    Thank you to Robin Zigmond for pointing me in the right direction. I was thinking that something was preventing the click event from firing, but it was simply not picking up on it because I needed to track the touchstart event.

    The linked answer does mention that a better solution was found by adding cursor:pointer; to the button with CSS, however my element already had that so it obviously didn't work in this case.

    Add this function to detect the taps on mobile:

    $('#submitButton').bind( "touchstart", function(e){
        if (attributeEqualsDisabled($(this).attr('disabled'))) {
            return true;
        }
        $("#submitButton").attr('disabled', true);
        $('#createForm').submit();
    });