John Sly
John Sly

Reputation: 769

mousemove to touchmove isn't working

I have a very simple script where two images overlay each other, then by sliding the mouse horizontally, the top image either fades or re-appears. This is used for a then/now mashup.

The script works perfect on desktop, but I can't get it to work on mobile. On mobile, the "mouse" is picked up only on the initial touch, but not the slide.

I've tried touch-punch.js, tried modifying my code to work with it, but so far I haven't had ANY luck at all...

Here's my code

<script type="text/javascript" language="JavaScript">

$(document).ready(function() {
    $('.trackMe').each(function(){
        //$(this).children("img:last").mousemove(function(e) {
        $(this).children("img:last").on("mousemove touchmove", function(e) {
            var offset = $(this).offset();
            var xpos = (e.pageX - offset.left);
            var ypos = (e.pageY - offset.top);
            //now to get the first child image width..
            var thisImage = $(this);
            var thisWidth = thisImage.width();
            var pct = Math.round((xpos/thisWidth)*100)/100;
            var ipct = Math.abs(Math.round(((xpos-thisWidth)/thisWidth)*100)/100);
            thisImage.css({ 'opacity' : ipct });
        });
    });
});

</script>

I don't have it publicly accessible, but the only components missing are the styles and an over/under image.

<style type="text/css">
    .trackMe img.packard {
        width:100% !important;
        top:0 !important;
        left:0 !important;
        position:absolute;
        margin:0 !important;
    }

    .trackMe img.now{
        width:100% !important;
        margin:0 !important;
    }
</style>

<div style="position:relative; min-width:320px; height:auto; overflow:hidden;" class="trackMe">
    <img src="1a.jpg" class="now" />
    <img src="1b.jpg" class="packard" />
</div>

Upvotes: 2

Views: 8951

Answers (1)

Devendra Soni
Devendra Soni

Reputation: 1934

hey try this in your code.. try to get the x and y like this

$(document).bind('touchmove mousemove', function (e) {

    var currentY = e.originalEvent.touches ?  e.originalEvent.touches[0].pageY : e.pageY;
      var currentX = e.originalEvent.touches ?  e.originalEvent.touches[0].pageX : e.pageX;
//do your stuff
});

thanks

Upvotes: 8

Related Questions