Reputation: 415
I have a not so unique problem I am running into. Currently utilizing the Google Maps API InfoBox. If a specific flag is set on this infobox the scroll is disabled. I need to have this flag set and there seems no way to dynamically change it.
The only way around this may be to use a pure JavaScript scrolling function. The standard CSS would be:
-webkit-overflow-scrolling: touch;
However this does not function per the flag above. I have also tried a number of JavaScript libraries but they just seem to be pretty versions of the standard CSS scroll.
Does anyone know of a library which uses only JavaScript to scroll inside of a div
?
answer
function touchScroll(id){
// if(isTouchDevice()){ //if touch events exist...
var el=document.getElementById(id);
var scrollStartPos=0;
document.getElementById(id).addEventListener("touchstart", function(event) {
scrollStartPos=this.scrollTop+event.touches[0].pageY;
event.preventDefault();
},false);
document.getElementById(id).addEventListener("touchmove", function(event) {
this.scrollTop=scrollStartPos-event.touches[0].pageY;
event.preventDefault();
},false);
// }
}
Upvotes: 0
Views: 127
Reputation: 11506
This function calls the isTouchDevice()
function, and if it succeeds a special touch events is attached to the page. First when a touch event begins (the touchstart
event) it get the current scroll position and prevent the default browser behavior, which in this case would be to scroll the page. Next when a finger is moved the touchmove
event is called. Here the position of your finger is subtract from the scroll position that was saved earlier and again prevent the page from scrolling.
function isTouchDevice(){
try{
document.createEvent("TouchEvent");
return true;
}catch(e){
return false;
}
}
So that’s it, just include these functions on your page and just call it by passing in the ID
of the element you want to scroll. Like so: touchScroll("MyElement");
.
function touchScroll(id){
if(isTouchDevice()){ //if touch events exist...
var el=document.getElementById(id);
var scrollStartPos=0;
document.getElementById(id).addEventListener("touchstart", function(event) {
scrollStartPos=this.scrollTop+event.touches[0].pageY;
event.preventDefault();
},false);
document.getElementById(id).addEventListener("touchmove", function(event) {
this.scrollTop=scrollStartPos-event.touches[0].pageY;
event.preventDefault();
},false);
}
}
Upvotes: 1