Dropdown V2

by Satheesh Kumar

HTML

<div>

<select data-plugin="myElement">
  <option value="one">One</option>
  <option value="two">Two</option>
  <option value="three">Three</option>
</select>

</div>
<div>

<select data-plugin="myElement">
  <option value="1">One One</option>
  <option value="2">Two Two</option>
  <option value="3">Three Three</option>
</select>

</div>

CSS

[data-dparent="myElement"]{
  color: red;
}
.hbl-dropdown_body{
  display: none;
}
.hbl-dropdown .hbl-dropdown_header{
  padding: 10px;
  max-width: 100%;
  border: 1px solid #cfcfcf;
}
.selected{
  color: green;
}

JavaScript

(function($) {
  // Define the plugin
  $.fn.myPlugin = function(options) {
    // Default settings
    var settings = $.extend(
      {
        message: 'Hello, World!',
        callback: null
      },
      options
    ),
    selector,selectorType, selectorParent, $element, selectorTarget,isOpen, selectedIndex	;

    // Plugin methods
    var methods = {
      init: function() {
        return this.each(function() {
          	 $element = $(this);
              isOpen = false;
          var $options = $element.next().find('.hbl-dropdown_child');
          	var selectedIndex = $element.prop('selectedIndex');

                   // Check if plugin is already initialized
              var isInitialized = $element.data('myPluginInitialized');
              if (isInitialized) {
                // Plugin is already initialized, call the method
                methods.myMethod.call(this);
                return; // Exit the initialization
              }

						 selector = selectorTypeFun(this);
          	 selectorType = selector[0];
						 selectorParent=selector[1];
         // createDropdown();
					  methods.createDropdown.call(this);;
            
            // Event: Keyboard navigation
          $(document).on('keydown', function(e) {
                          console.log('cdsvs', isOpen);
					if (isOpen) {
              var key = e.which || e.keyCode;
              var numOptions = $element.next().find('.hbl-dropdown_child').length;
							
              if (key === 40) {
                // Down arrow key pressed
                console.log(selectedIndex);
                updateSelectedOption();
                selectedIndex = (selectedIndex + 1) % numOptions;
                e.preventDefault();
              }
            }
          });
     
          // Call the callback function if provided
          if (typeof settings.callback === 'function') {
            settings.callback.call(this, settings.message);
          }
        });
      },
     ...