Skip to content

Instantly share code, notes, and snippets.

@zlove
Last active January 24, 2018 19:58
Show Gist options
  • Save zlove/eb95e9d51af5b55eb435 to your computer and use it in GitHub Desktop.
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.
;(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);
@zlove
Copy link
Author

zlove commented Aug 13, 2014

This could probably fairly easily be made into a more general purpose utility to wrap any jquery plugin where you want to do the same thing.

@tabarjack
Copy link

Thanks very much for this piece of brilliant code.

@birdkiwi
Copy link

Thank you!

@ratron
Copy link

ratron commented Jan 24, 2018

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)}```

@zlove
Copy link
Author

zlove commented Jan 24, 2018

Thanks @ratron! I made that change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment