Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple elements respond to touch event on mobile Webkit and Hammer JS

I'm working on a small side project using the Hammer JS library and I've ran into a problem on Chrome Dev Tools emulator and while debugging on two iOS 7 devices. It seems to work fine on desktop browsers. Fiddle here: http://jsfiddle.net/w80baz5g/5/ and more info below.

I've a group of elements, like this:

<div>
    <img class="item" id="item0" src="http://placehold.it/300x300">
    <img class="item" id="item1" src="http://placehold.it/300x300">
    <img class="item" id="item2" src="http://placehold.it/300x300">
</div>

and Hammer JS listening to a tap event:

function initItems(el) {
    var itemToTap = new Hammer.Manager(el, itemOptions);
            itemToTap.add( new Hammer.Tap() );
            itemToTap.on("tap", function(event) { 
                console.log("tapped: " + event.target);
        });

}

$(".item").each(function(){
    var itemToInit = $(this)[0];
    initItems(itemToInit);
});

While in desktop browsers (Chrome, Safari) everything seems fine, on mobile only the first out of three elements seems to respond to the tap event but the console shows it responds for all three elements? The second and third element are not responding at all.

Fiddle here: http://jsfiddle.net/w80baz5g/5/

Am I missing something? Are those events / elements treated differently by mobile browsers? Why aren't they responding individually to a tap event?

Help much appreciated!

like image 310
user1958639 Avatar asked Jan 19 '15 00:01

user1958639


1 Answers

Instead of:

$(".item").each(function(){
    var itemToInit = $(this)[0];
    initItems(itemToInit);
});

Try using:

$(".item[id^='item']")...

Or:

$("[id^='item']")...

And see what happens.

like image 171
Jose Luis T.R. Avatar answered Oct 07 '22 04:10

Jose Luis T.R.