metafizzy / flickity

:leaves: Touch, responsive, flickable carousels
https://flickity.metafizzy.co
7.52k stars 605 forks source link

Only propagate links on selected slide #812

Closed spwarner closed 6 years ago

spwarner commented 6 years ago

I'd like to have it so that if you click on any slide other than the selected slide, it jumps to that slide (as in the extras demo - easy). However, I have links on my slides and I'd like to have them be followed when clicked on, but only for the selected slide, links on other slides don't follow, they just jump to that slide.

desandro commented 6 years ago

I'm sorry to see you're having trouble with Flickity. Could you provide a reduced test case? See Submitting Issues in the contributing guidelines.

spwarner commented 6 years ago

This is a question/feature request, not a bug report, so I don't have a test case. I've tried a bunch of things but haven't been able to get this to work - hence the post. Sorry if this is in the wrong place.

desandro commented 6 years ago

Okay! All the same, if you can get things started with a CodePen demo that I or someone else can fork, I'd be better prepared to take a look at tackling this request.

Yes, this can be done.

spwarner commented 6 years ago

OK - I forked your staticClick demo and added in my first attempt at getting this working (but my method doesn't - seems like the staticClick fires first so .is-selected is already applied). Any other thoughts?

https://codepen.io/garudha/pen/JadoeN

desandro commented 6 years ago

Thanks for that. Here's one way to do it. See demo https://codepen.io/desandro/pen/f02150902d24e0df76ea2719e1c77c0b/

var $carousel = $('.carousel').flickity();

// prevent all link clicks
$('.carousel a').click(function( event ){
   event.preventDefault();
});

var flkty = $carousel.data('flickity');

$carousel.on( 'staticClick.flickity', function( event, pointer, cellElement, cellIndex ) {

  var $link = $( event.target ).closest('a');
  var isLink = $link.length;
  var isSelected = cellElement == flkty.selectedElement;
  // only follow links in selected cells
  if ( isLink && isSelected ) {
    window.location = $link[0].href;
  } else if ( typeof cellIndex == 'number' ) {
    $carousel.flickity( 'selectCell', cellIndex );
  }
});
spwarner commented 6 years ago

That works for me - thanks!