Jump to content
Search Community

Limit element translation to its bounds

eviljeff test
Moderator Tag

Recommended Posts

Hi,

 

I have an image bigger than the viewport that I'd like to move around using the keyboard arrows. I am having issues with stopping the image once the edges are reached.

 

I have tried with this function

 

function limits(){
  let drag = bigImage.getBoundingClientRect();
  var mn = 0;
  var mxY = drag.height;
  var mxX = drag.width;
  var tY = drag.y;
  var tX = drag.x;
  if(-tY < mn || -tY > mxY) {
    gsap.set(bigImage, {y: -tY > mxY ? mxY : "+=0"});
  };
  if(-tX < mn || -tX > mxX) {
    gsap.set(bigImage, {x: -tX > mxX ? mxX : "+=0"});
  };
};

But it doesn't do what I'm trying to achieve. I must be doing something wrong.

 

I have created a codepen to show the problem. I would really appreciate to have some help with this.

 

Thanks!

See the Pen eYMBoEO by jeffceriello (@jeffceriello) on CodePen

Link to comment
Share on other sites

I can't seem to get arrow keys to work with the codepen, but what I would do is create a function for horizontal and one for vertical movement that utilizes the .clamp() utility.

 

// THIS IS PSEUDO-ISH CODE AND WILL NOT WORK

const horizontalMove = (currentXPosition, direction) => {
	// some logic to get the next position
  	let nextPosition = currentXPosition + (dist * direction)
  	nextPosition = gsap.utils.clamp(maxLeft, maxRight, nextPosition);
  	
  	gsap.to(el, {x: nextPosition})
}

 

Link to comment
Share on other sites

Here's how I'd simplify it: 

See the Pen ExEZxOz?editors=0010 by GreenSock (@GreenSock) on CodePen

 

document.addEventListener("keyup", function(e) {
  let x, y;
  if (e.keyCode == 37) { // left arrow
    x = 100;
  } else if (e.keyCode == 38) { // up arrow
    y = 100;
  } else if (e.keyCode == 39) { // right arrow
    x = -100;
  } else if (e.keyCode == 40) { // down arrow
    y = -100;
  }
  if (x || y) { // if anything changed...
    let vars = {overwrite: true};
    if (x) {
      vars.x = gsap.utils.clamp(bigDraggable.minX, bigDraggable.maxX, gsap.getProperty(bigImage, "x") + x);
    } else {
      vars.y = gsap.utils.clamp(bigDraggable.minY, bigDraggable.maxY, gsap.getProperty(bigImage, "y") + y);
    }
    gsap.to(bigImage, vars);
    e.preventDefault();
  }
});

Does that help?

  • Like 2
Link to comment
Share on other sites

Hey Jack, that does help and it works really well!!

 

Once again, thank you so much!! I've learned a lot of gsap features from this project that I didn't know even existed.

 

You are a life saver. Thank you

 

 

  • Like 2
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
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...