javascriptiospreventdefaultibooks

event.preventDefault() in ibooks: Can anyone explain why this isn't working?


I'm trying to apply a preventDefault to a div in iBooks to create an area in which none of the touch/drag events for turning pages work. So far I've only tried to prevent the touch events, but it isn't working. I may be completely wrong in my implementation here:

var area = document.getElementById('area');
function touchStart(event) {
    event.preventDefault();
}
function touchMove(event) {
    event.preventDefault();
}
function touchEnd(event) {
    event.preventDefault();
}
function touchCancel(event) {
    event.preventDefault();
}

area.addEventListener("touchstart", touchStart, false);
area.addEventListener("touchmove", touchMove, false);
area.addEventListener("touchend", touchEnd, false);
area.addEventListener("touchcancel", touchCancel, false);

Any hints as to why this isn't preventing the touch events would be gratefully received.


Solution

  • You're close. In order to pass the event to the function you actually have to use an anonymous function.

    I think you should also not worry about creating the multiple functions instead just call the one line in the anonymous function.

    var area = document.getElementById('area');
    
    area.addEventListener("touchstart", function(event) {event.preventDefault()}, false);
    area.addEventListener("touchmove", function(event) {event.preventDefault()}, false);
    area.addEventListener("touchend", function(event) {event.preventDefault()}, false);
    area.addEventListener("touchcancel", function(event) {event.preventDefault()}, false);
    

    If you still want to go the route of having the event listener call your function it would look something like this:

    var area = document.getElementById('area');
    
    function myTouchStart(myEvent) {
        myEvent.preventDefault();
    }
    
    area.addEventListener("touchstart", function(event) {myTouchStart(event)}, false);
    

    The idea is that the event listener has an anonymous function that you than call your function through. With anonymous functions you can declare the event object to be passed to the anonymous function and on to your own.