Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>What I had before was just not working so I started with a script that detected the x position of the mouse and change the width accordingly.</p> <pre><code>var oldXPos = 0; var isDragging = false; $(document).mousemove(function(event) { if (isDragging) { var difference = event.pageX - oldXPos; $('#changeMe').css({width: '+='+ difference}); } oldXPos = event.pageX; $('#changeMe').mousedown(function(){isDragging = true;}) $('#changeMe').mouseup(function(){isDragging = false;}) }); </code></pre> <p>But I also wanted to have it work on a touch device. So I bond the events to touchmove, touchstart and touchend. I also had to change the listener for the mouse position.</p> <pre><code> oldXPos = event.originalEvent.targetTouches[0].pageX; </code></pre> <p>This allow me to get the current position of the touch event. This worked ok but you had to tap and the tap and drag to get it to work. So I bond an event listener to the element itself, after the dom was ready. So that every time there was a touchstart event it would find the position of that event.</p> <pre><code>$(document).ready(function(){ $('#changeMe').bind('touchstart', function(event){ oldXPos = event.originalEvent.targetTouches[0].pageX; }); }); </code></pre> <p>This worked perfectly except that you had to keep your finger on a straight line or else the screen would "scroll". So I had to prevent the touchmove defaults when you were in the element and the "re-enable" default when you stopped. </p> <pre><code>$(document).ready(function(){ $('#changeMe').bind('touchstart', function(event){ oldXPos = event.originalEvent.targetTouches[0].pageX; $('body').bind('touchmove', function(e){e.preventDefault()}); }); }); </code></pre> <p>The final code...</p> <pre><code>&lt;style&gt; .outer{width:500px; height:200px; overflow:hidden; } #changeMe {width:1000px; height: 200px;} &lt;/style&gt; &lt;div class="outer"&gt; &lt;div id="changeMe"&gt; Some Content &lt;/div&gt; &lt;/div&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" &gt;&lt;/script&gt; &lt;script&gt; $(document).bind('touchmove' ,function(event) { if (isDragging) { var difference = event.originalEvent.targetTouches[0].pageX - oldXPos; $('#changeMe').css({width: '+='+ difference}); } oldXPos = event.originalEvent.targetTouches[0].pageX; $('#changeMe').bind('touchstart', function(){isDragging = true;}) $('#changeMe').bind('touchend', function(){isDragging = false;}) }); $(document).ready(function(){ $('#changeMe').bind('touchstart', function(event){ oldXPos = event.originalEvent.targetTouches[0].pageX; $('body').bind('touchmove', function(e){e.preventDefault()}); }); }); &lt;/script&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload