javascript - Event touchstart doesn't work on iPhone -


i have code works, except on iphone. when window loads, function called. when have event click, works fine on desktop, not on mobile. i've tried looking around solutions mobile, , touchstart seems recommended solution. but, though works on emulators, doesn't work on iphone (tested on latest os version). missing something?

function addxclassonclick() {   var els = document.getelementsbyclassname('item');    array.prototype.foreach.call(els, function(el) {     el.addeventlistener('touchstart', function() {       el.parentelement.classlist.toggle('x');     }, false);   }); } 

thanks in advance!

given document fragment:

<div class="x">     <div class="item">item</div> </div> 

the anonymous event handler function's default scope bound clicked element, , not clicked element's parent, scope classlist.toggle should operate on.

(edit: according documentation, foreach passes undefined in scope of callback function when not specified. dom element reference el has no scope operate in. it's dom there, scope chain isn't.)

to fix this, either call classlist.toggle correct scope:

el.parentelement.classlist.toggle.call(el.parentelement.classlist, 'x'); 

or call foreach desired scope second argument:

array.prototype.foreach.call(els, function(el) {     // omit }, els); 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -