Jump to content

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

Draggable slider breaks on resize

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

With this function I create a slider:

	function createDragger() {
		dragger && dragger[0].kill()
		dragger = Draggable.create( wrapper, {
			throwProps: true, 
			bounds: document.querySelector( '.image-slider__container' ),
			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] ) ]
			maxDuration: .4,
			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
	} )

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.