Search code examples
javascriptjqueryjquery-uijquery-ui-slider

Jquery UI slider options object


I am attempting to use the jQuery UI slider in a project. I have a need to create sliders with different options and I am attempting to use the option method.

I have done the following:

HTML

<div class="slider" data-a-orientation="vertical"></div>

I am placing the slider options as data attributes in HTML and then retrieving them with jQuery

JS

init : function(element)
        {
            this.elem = element;
            this.$elem = $(element);
            // target element
            this.slider_target = this.$elem.find('.slider');
        
        /*
         * Get all the data-attr from the .slider target element    
         * if there is any
         * loop over all and create an object of options. Note all our data attr 
         * are -a- separated. 
         */
        var slider_opt_obj = {};
        $.each(this.slider_target.data(), function(key, val){
            // note ! ~ each of the data attributes are : data-a-attribute_title 
            // we need to remove a .. the - character is already removed
            // this was added to stop any overwriting by the jQuery ui plugin
            var key_lwr = key.toLowerCase();
            slider_opt_obj[key_lwr.slice(1)] = val;
        });
        
        // create the sliders
        this.sliderCreate( this.slider_target, slider_opt_obj);
    },
    sliderCreate : function(target, options)
    {
        var self = this;
        
        if( !self.objectEmpty(options) ) {
            // does not work throws error
            target.slider("option", options);
        } else  {
            // no options
            target.slider();
        }
    }

This line

target.slider("option", options);

is causing the following error

Error: cannot call methods on slider prior to initialization; attempted to call method 'option'

According to the jQuery ui docs the method option does accept a object .. what am I missing here ?

Also jsFiddle


Solution

  • You can't call .slider("option", options) before the slider is created. Just create the slider with your options object as the parameter:

    target.slider(options);