Jump to content
Search Community

Toggle Switch with Draggable and snap

Gary Griswold test
Moderator Tag

Go to solution Solved by GreenSock,

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

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 comment
Share on other sites

  • Solution

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 comment
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 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...