I'm using the following Javascript to create ontouchstart/move/end callbacks on div elements for an iOS web app. The only problem at the moment is that when you try to scroll up and down the page, it triggers the ontouchstart element and changes the CSS of the div. I want the CSS of the div to change only when a user selects the item. I'm fairly basic with Javascript but if anyone knows any way of getting the Javascript to only trigger when a user is selecting an item it would be greatly appreciated!
Thanks!
TC
Javascript:
function onclickCallback( event ) {
}
function ontouchstartCallback( event ) {
event.target.className = 'choice_link_selected';
}
function ontouchmoveCallback( event ) {
event.target.className = 'choice_link_selected';
}
function ontouchendCallback( event ) {
event.target.className = 'choice_link';
}
HTML:
<div class="choice_link" onclick="onclickCallback(event);" ontouchstart="ontouchstartCallback(event);" ontouchend="ontouchendCallback(event);" ontouchmove="ontouchmoveCallback(event);">
<a href="javascript:location.href='test.php'">Test</a>
</div>
As far as I know, it's correct to use just the
onmousemove
handler to swap theclassName
to the default state. The problem of your button state freeze during iPhone scrolling is related to another issue: when you try to scroll your view, any interaction with the page rendering is locked to perform a scroll with good performance and avoid conflicts. Then the content of the page looks freezed. That's why your button cannot restored to the default state before the scrolling.The sad thing is that this behaviour depends on how you start the scroll. If you scroll on the div area and the button div can dispatch a
touchmove
event before the scrolling process, it works, otherwise the css class will be restored when the scrolling will be completed.Some JavaScript touch frameworks solve this by catching the touches events and prevent default browser behaviours (like the scrolling) and implement their own scrolling system.
I know, it's not a solution but could be an explanation.
Hope it helps. Ciao.
Assuming I'm understanding what you're asking:
Add to ontouchstartCallback:
Replace contents of ontouchmoveCallback with:
What this is doing:
When a touch event begins, the X/Y coords are attached to the touched DOM element. Then on every move event, it checks to see if the movement is more than a certain threshold of pixels away (5 in this case). If so, we change back the class prematurely, and remove the X/Y coords, as we don't need them anymore.
use
event.stopPropagation()
to stop the event bubbling, and useevent.preventDefault()
to avoid the default handler.