mhartington
mhartington

Reputation: 7025

simulating mouse drap /touch drag movement in javascript

So I have some javascript that when a person clicks and drags or drags their finger (on mobile devices) and cycles though a series of images to create a 360 image rotation effect. Heres the code.

    $(document).ready(function ($) {
    var $product = $('#product'),
        $imgs = $product.find(".child"),
        imageTotal = $imgs.length - 1,
        clicked = false,
        widthStep = 20,
        currPos,
        currImg = 0,
        lastImg = 0;
    $imgs.bind('mousedown', function (e) {
        e.preventDefault(); // prevent dragging images
    })
        .filter(':gt(0)').addClass('notseen');

    $product.bind('mousedown touchstart', function (e) {
        if (e.type == "touchstart") {
            currPos = window.event.touches[0].pageX;
        } else {
            currPos = e.pageX;
        }
        clicked = true;

    });
    $(document)
        .bind('mouseup touchend', function () {
        clicked = false;
    })
        .bind('mousemove touchmove', function (e) {
        if (clicked) {
            var pageX;
            if (e.type == "touchmove") {
                pageX = window.event.targetTouches[0].pageX;
            } else {
                pageX = e.pageX;
            }
            widthStep = 20;
            if (Math.abs(currPos - pageX) >= widthStep) {
                if (currPos - pageX >= widthStep) {
                    currImg++;
                   if (currImg > imageTotal) {
                     currImg = 0;}
                } else {
                    currImg--;
                    if (currImg < 1) {
                        currImg = imageTotal;
                    }
                }
                currPos = pageX;
                $imgs.eq(lastImg).addClass('notseen');
                $imgs.eq(currImg).removeClass('notseen');
                lastImg = currImg;
                // $obj.html('<img src="' + aImages[options.currImg] + '" />');
            }
        }
    });
});

Now using this as a basis, I want to simulate the mouse or finger being draged a certain distance once the document is loaded, I wanted to simulate this function to create an automatic rotation.

Now I know I need to use the mousedown/touchstart and mousemove/touchmove functions in this, but from there I'm kind of lost on how to start it and set the simulated distance. Any ideas and help is appreciated.

Upvotes: 0

Views: 1318

Answers (1)

dm03514
dm03514

Reputation: 55962

An easy way is to refactor your code to expose the touchstart and touchmove as their own functions/objects.

This will allow you to call them from anywhere, under any circumstance, and not have to rely on the actual events firing.

I recently read an awesome article which explains some suggestions on how to effectively do this: https://shanetomlinson.com/2013/testing-javascript-frontend-part-1-anti-patterns-and-fixes/

Upvotes: 1

Related Questions