Last active
January 24, 2018 19:58
-
-
Save zlove/eb95e9d51af5b55eb435 to your computer and use it in GitHub Desktop.
Wrap bxSlider so that we can override options per slider with data attributes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function ($) { | |
/** | |
* Return an object consisting of properties of 'data' | |
* that match the regex 'pattern'. If trim is not false, | |
* trim the matched 'pattern' from the property name, | |
* and make the first char of the remaining property | |
* name lowercase. | |
*/ | |
function filterData(data, pattern, trim) { | |
var data, | |
prop, new_prop, | |
matched_data = {}; | |
for (prop in data) { | |
if (data.hasOwnProperty(prop) && prop.match(pattern) ) { | |
if (trim) { | |
new_prop = prop.replace(pattern, ''); | |
if ( ! new_prop.length ) { | |
continue; | |
} | |
new_prop = new_prop.charAt(0).toLowerCase() + new_prop.slice(1); | |
matched_data[new_prop] = data[prop]; | |
} else { | |
matched_data[prop] = data[prop]; | |
} | |
} | |
} | |
return matched_data; | |
} | |
/** | |
* Example Usage: | |
* | |
* js: | |
* $('.slider-element').bxSliderAlt({ slideWidth: 200 }) | |
* | |
* html: | |
* <div class="slider-element" data-bx-slider-pager="false" data-bx-slider-slide-width="300"> | |
* ... | |
* </div> | |
*/ | |
$.fn.bxSliderAlt = function (options) { | |
if(this.length == 0) return this; | |
if (typeof(options) == 'undefined') { | |
options = {}; | |
} | |
this.each( function() { | |
var data_options = filterData($(this).data(), /bxSlider/, true); | |
var custom_options = $.extend({}, options, data_options); | |
$(this).bxSlider(custom_options); | |
}); | |
} | |
})(jQuery); |
Thank you!
there is a bug:
#53 $.extend(options, data_options);
will change the original options object and all subsequent sliders will have all previous options. each slider should be initialized with it's own object. like so:
var custom_options = {}
$.extend(custom_options, options, data_options);
$(this).bxSlider(custom_options)}```
Thanks @ratron! I made that change.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks very much for this piece of brilliant code.