开发者

Simulate scroll event using Javascript

I am trying to Simulate a scroll event using Javascript for Mobile Safari. I am using the following code

var evt = document.createEvent("MouseEvents");    
evt.initMouseEvent("scroll", true, true, window,0, 0, 0, 0, 0, fals开发者_开发知识库e, false, false, false, 0, null);

The above code is part of a jQuery plugin jQuery.UI.Ipad which basically maps touch events like touchstart, touchmove, touchend to mouse events like mouseover, mousedown, etc

However for some reasons the code for simulating a scroll event is not working... Please help me. So essentially my question is how do I simulate the scroll event.


I think people are confused as to why you would overide the scroll control. I can see why you want to imitate mouse events, but scroll maybe should not be one of them.

Usually for scroll changes you can just get the scroll with:

var top = document.body.scrollTop;

And set with:

document.body.scrollLeft = sX;
document.body.scrollTop = sY;


So, I know I' need to simulate it too. for me it's when you have a lightbox with a overflow box that you would need it. Just one case of many I can think of. looking to for an answer. Just thought I'd share where I'm at, thou not with the jQuery.Ui.Ipad I will Google that.. but here is what I got so far and does work but not perfectly.

    var inTouch=false;
    var timers_arr = new Array();
    var c=0;
    var t;
    var timer_is_on=0;
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------
    // jeremy's timer functions
    //-------------------------------------------------------------------------------------------------------------------------------------------------------------
        function clearCount(timer){
                /// clear the time from timer
                clearTimeout(timers_arr[timer]);
                /// Make sure it's clear  
                timers_arr[''+timer+'']=0;
                delete timers_arr[''+timer+''];

        }
        function setCount(timer,time,func){
                clearCount(timer);
                if(timers_arr[timer]==0||typeof(timers_arr[timer]) === 'undefined'){
                  timers_arr[timer]=setTimeout(function(){
                                        func();                                                 
                        },time);
                }
        }

    function updatePos(evt,startY){
        setCount('touchmove',1,function(){
            var orig = evt.originalEvent;
            var curY = orig.changedTouches[0].pageY;
            var y = curY - startY;
            var sliderVal = $("#slider-vertical").slider("value");
            sliderVal += (y*.008);
            $("#slider-vertical").slider("value", sliderVal);
            updatePos(evt,startY);
        });
        setCount('touchmove_anitMotion',200,function(){
            clearCount('touchmove');
            clearCount('touchmove_anitMotion');
        });
    }
    var startX=0;
    var startY=0;
    var x=0;
    var y=0;
    var direction='';
    $('body').bind("onorientationchange", updateOrientation, false);
    $('#scroll-pane').live("touchstart", function(evt){
       inTouch=true;
       startX = event.targetTouches[0].pageX; 
       startY = event.targetTouches[0].pageY; 
    }); 
    $('#scroll-pane').live("touchmove", function(evt){
        evt.stopPropagation();
        evt.preventDefault();
        updatePos(evt,startY);
    }); 
    $('#scroll-pane').live("touchend", function(evt){
        startX=0;
        startY=0;
        clearCount('touchmove');
        inTouch=false;
    }); 
    $('#scroll-pane').live("touchcancel", function(evt){
        startX=0;
        startY=0;
        clearCount('touchmove');
        inTouch=false;
    });

Again not perfect and looking to fix it.. but it's at the least working. Now note, this is a div that is using the jQuery UI slider for a scroll bar as (thou in mine it's vertical) shown in

http://jqueryui.com/demos/slider/#side-scroll

Hope that spurs some ideas. If I get a super stable answer I'll get back. Cheers -Jeremy


I needed this to write a unit test , for which i need to simulate a scroll event

function dispatchScroll(target,newScrollTop) {
      target.scrollTop = newScrollTop;
      var e = document.createEvent("UIEvents");
      // creates a scroll event that bubbles, can be cancelled,
      // and with its view and detail property initialized to window and 1,
      // respectively
      e.initUIEvent("scroll", true, true, window, 1);
      target.dispatchEvent(e);
    }

For more details : https://developer.mozilla.org/en-US/docs/Web/API/event.initUIEvent


The event that worked for me was mousewheel, and the 5th parameter needs to be positive for scrolldown and negative for scrollup.

var evt = document.createEvent("MouseEvents");    
evt.initMouseEvent("mousewheel", true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);

Note that the event type is DOMMouseScroll for FireFox.


Events should now be created with CustomEvent as such new CustomEvent("wheel", { detail: { deltaY: 1 } }). document.createEvent is deprecated

https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent

I built this utility function that scrolls by 1 pixel every frame

const startFakeScrolling = (container: HTMLDivElement) => {
  const cb = () => {
    container.dispatchEvent(
      new CustomEvent("wheel", { detail: { deltaY: 1 } })
    );
    window.requestAnimationFrame(cb);
  };
  window.requestAnimationFrame(cb);
};

You will also need to modify the event listener to use detail, as deltaY will be undefined

const delta = e.deltaY != null ? e.deltaY : (e.detail as any).deltaY;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜