Jump to content

JS Touch Event - Controlling the amount of horizontal movement of the element


kayut

Recommended Posts

Hi,

I'm just learning the JavaScript touch event. For this I created this example:

Example on Codepen

In the above example, you can grab the element and move it to the right or left.

It works. However I want to limit the horizontal movement of the element (for example only 100px to the left and 100px to the right).

How can I do this?

Thanks

Link to comment
Share on other sites

First, find your limits:

var leftLimit = init_pos[0] - 100;
var rightLimit = init_pos[0] + 100;

Then store the currently calculated position:

var newX = init_pos[0] + e.pageX - drag_start [0];

If the position is within the limits, use that position, otherwise use the limit.

if(newX < leftLimit) {
  newX = leftLimit;
}
if(newX > rightLimit) {
  newX = rightLimit;
}

Finally, set the style of the element:

drag_target.style.left = newX + "px";

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...