Bind 'touchstart' event in jQuery not working with android phonegap and backbone

mabounassif picture mabounassif · Apr 3, 2012 · Viewed 10.4k times · Source

I have the following template in Backbone, all gets rendered perfectly.

    <a href="#list" data-role="button" id="button" class="all-unselected"></a>
    <a href="#" data-role="button" id="button" class="suggested-unselected"></a>
    <a href="#" data-role="button" id="button" class="friends-unselected"></a>
    <a href="#" data-role="button" id="button" class="private-unselected"></a>
    <a href="#" data-role="button" id="button" class="buzz-unselected"></a>
    <script type="text/javascript">
        var buttons = $("a#button");

        for(var i=0; i<buttons.length; i++){
            $(buttons[i]).bind('touchstart', select, false);
            $(buttons[i]).bind('touchend', unselect, false);
        }

        function select(){
            alert('test');
        }
        function unselect(){
            alert('unselect');
        }
    </script>

The touchstart doesn't get triggered however if I write the following:

    <a href="#" data-role="button" id="button1" class="suggested-unselected"></a>
    <script type="text/javascript">
            document.getElementById('button1').addEventListener('touchstart', select, false);

        function select(){
            alert('test');
        }
        function unselect(){
            alert('unselect');
        }
    </script> 

it works. As if jQuery can't bind the event. What might be the problem?

Answer

m90 picture m90 · Apr 3, 2012

There are a couple of issues in your code.

First of all:

var buttons = $("a#button");

This selects an anchor element with the id button. As ids should be unique, this should only return one element. Yet, you are trying to loop through the returned value. That should not be working the way you are trying to do it.

Second:

If you have a set of jQuery object that you have selected you usually use .each() to iterate over them. Yet, if you are trying to bind an event handler to a set of objects you don't even have to do this in a loop as jQuery is able to bind an event to a selection.

Third:

.bind()-ing works different, you are mixing .bind() - syntax with addEventListener syntax.

So, to translate your working non-jQuery-example (it's not bad not to use jQuery btw) into jQuery this would look like:

$('#button1').bind('touchstart', select);
$('#button1').bind('touchend', unselect);

function select(){
alert('test');
}

function unselect(){
alert('unselect');
}