Create Custom Dropdown using jQuery

We use “select” field of HTML while creating forms. But, sometimes we want to customize this “select” field as per our need. We cannot apply custom look and feel to select field. For that we need to create a custom dropdown. In this example, we are creating dropdown using custom jQuery plugin.

Create custom jQuery plugin

To create a custom plugin we need to create a function which is shown below. This indicates the name of your jQuery plugin.

$.fn.custom_dropdown = function(){
        
    // Your plugin code here….

     return this.each(function() {
            // Initialize Custom Dropdown Plugin
     });
    
};
$("#dropdown").custom_dropdown();

In this way you can call your jQuery plugin. This creates a custom dropdown inside “#dropdown” div.

Passing options/properties to jQuery plugin

$.fn.custom_dropdown = function(options) {
     
        var _defaults={
            
            drpOptions:[],
            optionText:"Select State",
            drpName: "custom_dropdown",
            slideTime:500,
            template: "<div class='drpDown'>"+
                          "<div class='selectedOption'></div>"+
                            "<div class='drop_btn' tabindex='0'></div>"+
                            "<div class='clearCB'></div>"+
                            "<ul class='select_drop_down'>"+
                            "</ul>"+
                          "<input type='hidden' val='' />"+
                      "</div>",
            
        };    
};

These are default parameters to our custom dropdown plugin.

  1. drpOptions:
    Type: Array
    – This is an array consisting of all options in custom dropdown.

  2. optionText:
    Type: String
    – This is default text in dropdown. If not provided it will use “Select State” as default value.

  3. drpName:
    Type: String
    – Name of the dropdown. This will override name of input field present in custom dropdown template parameter.

  4. slideTime:
    Type: Number
    – This is time to close and open all dropdown options. This is optional field. Default slideTime is 500 ms.

  5. template:
    Type: String
    – This is custom dropdown HTML template. You cannot override this.

Template consists of ‘selectedOption’ div which will show selected option from dropdown.
‘drop_btn’ div is to expand and close dropdown. There is ‘select_drop_down’ list here we will populate all dropdown options from drpOptions array.

$.fn. custom_dropdown = function(){
        
    // Your plugin code here….

        var _self=this;
        var _settings = $.extend( {}, _defaults, options );
        
        // initialize custom_dropsown
        var _init=function(){
            _setTemplate();
            _setEvents();
        };
};

Assign current (this) object to _self variable to avoid confusion. This object contains current jOuery selector to which you have applied custom dropdown plugin. For example, if you are using below code

$("#dropdown").custom_dropdown();

Then “this” variable contains #dropdown selector.

Except template property all other properties are optional. If you are not passing any property to your custom dropdown then default properties will be used. $.extend function will merge option object passed by user and _defaults object. So _settings will be merged object which contains both properties from option as well as _defaults. Properties in _defaults object will be overriden by option object.

_init function will initialize our custom dropdown plugin. This will also call _setTemplate and _setEvents functions.

var _setTemplate=function(){
           
            _self.empty();
            // append template to selector
            _self.append(_settings.template);
            var drpListEle=  _self.find(".select_drop_down");
            _self.find("input").attr("name",_settings.drpName);
            _self.find(".selectedOption").text(_settings.optionText);

            // Iterate drpOptions array and create list options
            $.each(_settings.drpOptions,function(index,value){
                if(index==0) drpListEle.append("<li tabindex='"+(index+1)+"' value='"+_settings.optionText+"'>"+_settings.optionText+"</li>")
             // append list option to ul tag
                else  drpListEle.append("<li tabindex='"+(index+1)+"' value='"+value+"'>"+value+"</li>")
            });
        };

In above code, we have used $.each function which iterates all drpOptions array and append all items to “.select_drop_down” list. This will set up our UI part of custom dropdown. Next we will bind events to our custom dropdown elements.

$.fn. custom_dropdown = function(){
        
    // Your plugin code here….

var _setEvents=function(){
            var drpBtn=  _self.find(".drop_btn");
            var drpOption=_self.find(".select_drop_down li");
            var drpSelectedOption= _self.find(".selectedOption");
            var drpInput=_self.find("input");
            var drpList=_self.find("ul");
            
            // Handle dropDown click event
            drpBtn.click(function(){
                  // toggle state of all options
                 drpList.slideToggle(_settings.slideTime)                     
            });

             // Handle option click event
            drpOption.click(function(){
                  drpSelectedOption.text($(this).text());
                  drpInput.val($(this).text())
                  // hide all options
                  drpList.slideUp(_settings.slideTime)
                  // Reseting styles of all options
                  drpOption.removeAttr("style");
            });
            
            
            // Handle option hover event
            drpOption.hover(function(){
                 drpOption.removeAttr("style");
                 $(this).css("background-color","#EEE");   
            });
            
            
        };
};

In _setEvents function, we are binding click to down arrow button. This will toggle state of all options in dropdown. On hover, we are just highlighting each option in dropdown. We are using jQuery slideToggle function to open and close dropdown options. You can change slideTime by overriding slideTime property in _defaults object. There is hidden field in this we are storing value of selected option. You can use it as a form variable while creating forms.

Demo

Download custom_dropdown plugin here…

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>