Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
Gary Griswold

Toggle Switch with Draggable and snap

Go to solution Solved by GreenSock,

Recommended Posts

Hi,

 

I have written a toggle switch using draggable with the snap property set to the dimensions of the slider.  For example: snap:[0,47] works just fine.  But because I am developing for mobile I cannot use hardcoded dimensions.  

 

So, I have tried setting the snap after Draggable.create as follows:

 

    var drag0 = draggable[0];

    drag0.snap = [drag0.minX, drag0.maxX];

 

But, this does not seem to work.  Is there a way to make this work?

 

P.S. This is my first code pen. 

See the Pen QjzLdQ by garygriswold (@garygriswold) on CodePen

Link to post
Share on other sites

Hi Gary Griswold :)

 

pls try like this :

 

var drag0 = draggable[0];

drag0.vars.snap=[drag0.minX,drag0.maxX];
  • Like 1
Link to post
Share on other sites

You're trying to use minX/maxX before they've even been defined (which happens when you press down...each time). Remember, those values could change based on the position of the bounding element, for example. So it's dynamically set on each press/touch. 

 

The best approach would probably be to define a liveSnap like this: 

liveSnap: function(v) {
    return (v - this.minX < (this.maxX - this.minX) / 2) ? this.minX : this.maxX;
}

Does that help?

  • Like 3
Link to post
Share on other sites

Both of these solutions work great, but I do like using the function better, and I was able to move code that I had inside the onDrag function into the snap function.  However, when I used the 'liveSnap' property as you show here, the toggle would snap instantly from one side to the other.  But, when I used the 'snap' property it does glide gracefully.

 

Thanks so much.

Link to post
Share on other sites

Great. You've got options :) I thought the whole idea was that you wanted it to snap to one side or the other. But yeah, you should be able to get pretty much any effect you want with the current API :) 

 

Have fun!

Link to post
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.

×