Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
meesrttn

Draggable slider breaks on resize

Recommended Posts

With this function I create a slider:

	function createDragger() {
		dragger && dragger[0].kill()
		
		dragger = Draggable.create( wrapper, {
			type:'x', 
			edgeResistance:0.5, 
			throwProps: true, 
			bounds: document.querySelector( '.image-slider__container' ),
			lockAxis:true,
			zIndexBoost: false,
			snap: function( value ) {
				const curIndex = getClosestIndex( this.startX, bounds, bigNum, -bigNum ),
					prevIndex = curIndex ? curIndex - 1 : 0,
					nextIndex = ( curIndex === bounds.length - 1 ) ? curIndex : curIndex + 1
				return bounds[ getClosestIndex( value, bounds, bounds[prevIndex], bounds[nextIndex] ) ]
			},
			minimumMovement:6,
			maxDuration: .4,
			overshootTolerance:0.05,
			onThrowComplete: function()
			{
				currentActive = Math.floor( this.x / ( -( slideWidth * 5 ) / ( slides.length - 1 ) ) )
				const active = document.querySelector( '.image-slider__card.active' )
				if( active ) active.classList.remove( 'active' )
				slides[currentActive].classList.add( 'active' )
				setPagination( currentActive )
			},	  
		} )	
		dragger[0].startX = 0
	}

Then this optimizedResize function fires on resize.

	optimizedResize.add( () => {
		bounds = slides.map( item => -item.getBoundingClientRect().left )
		slideWidth = slides[0].getBoundingClientRect().width
		createDragger()
	} )

But when resizing the view of the slider remains the same and breaks.

Does anyone know how to keep the slides neatly in their view?

 

See the Pen rPNRjj by meesrutten (@meesrutten) on CodePen

Link to comment
Share on other sites

25 minutes ago, meesrttn said:

Does anyone know how to keep the slides neatly in their view?

 

getBoundingClientRect is going to give you incorrect results if you're not on the first slide. Try something like this on resize.

  • save current slide index
  • move to first slide
  • calculate bounds
  • move back to current slide

 

  • Like 3
Link to comment
Share on other sites

Added changes to CodePen, now works as expected!

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