1

I want to add either a scroll event listener or a touchstart event listener. Initially I used the touch event to deactivate the scroll event listener as shown in the code below:

window.addEventListener('scroll', scrollStart, false);
window.addEventListener('touchstart', touchStart, false);

function scrollMenu() {
    // do something
}

function touchStart(e) {
    window.removeEventListener('scroll', scrollStart);
    // do something
}

But I realized that on some occasions, the scroll event is triggered as soon as the page loads. Therefore, I cannot use the aforementioned method. Is there another way to check if the browser supports a touch event listener without adding the event?

2 Answers 2

4

Does Modernizr solve your problem? See example here for the various ways to detect touch events and each one's browser compatibility:

http://modernizr.github.com/Modernizr/touch.html

Sign up to request clarification or add additional context in comments.

3 Comments

You should really include a summary of the detection methods mentioned in that link; what happens if the page goes down in the future? (see here)
There are many methods, do I need to implement all or is ontouchstart in window the only relevant one?
You should probably do a browser check and use the method most appropriate to that browser. If you are only supporting a single browser, use the one that works for that browser.
3

You should be able to check whether the ontouchstart attribute exists in the window:

if ("ontouchstart" in window) {
    window.addEventListener('touchstart', touchStart, false);
} else {
    window.addEventListener('scroll', scrollStart, false);
}

... I can't confirm the x-browser-ness of this though.

1 Comment

Wow, this looks promising. Let me test it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.