flickity icon indicating copy to clipboard operation
flickity copied to clipboard

Set Option based on Parent class

Open dom-turnbull opened this issue 11 years ago • 6 comments

Due to the way I integrate Flickity in to the code (it's generated automatically through a jQuery .each()), I was wondering if there was a way to enable a property depending on whether or not a parent .hasClass().

dom-turnbull avatar Feb 13 '15 14:02 dom-turnbull

Mind pasting that code so I have a better idea?

If you're already using .each() then I'd recommend initializing with jQuery. This example code uses jQuery .each(), but also incorporates a data attribute for setting per-element options.

var flickityOptions = {
  // default flickity options
  cellSelector: '.gallery-cell'
};

$('.gallery').each( function( i, gallery ) {
  var $gallery = $( gallery );
  // get any options set in data-flickity-options attribute
  var optionsAttr = $gallery.attr('data-flickity-options');
  var dataOptions = optionsAttr ? JSON.parse( optionsAttr ) : {};
  // extend on default options
  var galleryOptions = $.extend( flickityOptions, dataOptions );
  // init flickity
  $gallery.flickity( galleryOptions );
});

desandro avatar Feb 13 '15 15:02 desandro

$('.mk-device').each(function(index, el) { 
  if ( $( el ).hasClass('mk-phone') ) { 
    var thisHtml = $( el ).html(); 
    $( el ).html(mkPhoneBefore + thisHtml + mkPhoneAfter);
    mkFlickityInit( el );
  } else if ( $( el ).hasClass('mk-tablet') ) {
     var thisHtml = $( el ).html();
     $( el ).html(mkTabletBefore + thisHtml + mkTabletAfter); 
     mkFlickityInit();

The mkFlickityInit(); function is:

function mkFlickityInit ( el ) { 
  $( el ).find('.mk-screen').flickity({  
    cellSelector: '.mk-slide',
    friction: 0.3,
    wrapAround: true 
    autoPlay: 5000,
  });
};

What I'm aiming for is for someone to be able to add a class to .mk-device called mk-autoplay which would toggle autoPlay on. I can't work out how to get that one to work. Ideally, I'd rather do it class based instead of using the data-flickity-options.

dom-turnbull avatar Feb 13 '15 15:02 dom-turnbull

Try this:

function mkFlickityInit ( el ) { 
  var $el = $( el );
  $el.find('.mk-screen').flickity({  
    cellSelector: '.mk-slide',
    friction: 0.3,
    wrapAround: true,
    autoPlay: $el.hasClass('.mk-autoplay') ? 5000 : false
  });
}

desandro avatar Feb 14 '15 01:02 desandro

Tried putting that in but just getting an undefined is not a function error instead.

dom-turnbull avatar Feb 16 '15 15:02 dom-turnbull

I think I missed a comma. Try again

desandro avatar Feb 16 '15 15:02 desandro

Yeah, that's sorted it. Cheers man.

dom-turnbull avatar Feb 16 '15 15:02 dom-turnbull