Jquery ui widget simple yet elegant example

Author - Mitul Marsonia

Purpose of the demo

jQuery UI is hidden Gem for making components. This simple example of jQuery UI widget is just the learning purpose for making component in jQuery.

To use jQuery in object oriented way there is only option of jQuery UI widget. By using that, we can make individual component and use it repeatedly just like jQuery UI calendar, slider and drag-drop. 

To make this demo, I have taken reference from the Widget Factory. Widget factory provides jQuery-UI API documentation. But their current example  Widget Factory is very complex. 

So we have just created a small component for demo purpose it’s just doing addition/subtraction in calendar like control for input field. 

Here is how it will look

Jquery Simple Widget

Let’s dive into the code without wasting time

Here is the HTML building block used to create this widget:

<div id="my-widget">
  <button type="button" class="btn btn-info my-widget-minus">-</button>
  <p class="my-widget-value"></p>
  <button type="button" class="btn btn-info my-widget-plus">+</button>	
</div>

Now we are going to create our custom widget, widget name is mywidget. 

 -> A widget is created by calling $.widget() with the name of the widget and an object containing its instance methods. 

-> We will work with just the name and prototype arguments. For the mywidget, our basic widget stub looks like the following:

$.widget("custom.mywidget", {
  // default options
  options: {
    myvalue: 0
  },
  _create: function () {
    $(this.element).val(this.options.myvalue);
    $(this.element).addClass("my-widget-input")
    this._on(this.element, {
      "focus": function (event) {
         // console.log({ event });
         var input_position = $(event.target).offset();
         var targetHeight = $(event.target).height() + 6;
         var targetWidth = ($(event.target).width() - 2);

         this._generateHtml();
         // console.log({ input_position });
         $("#my-widget";).css({ //widget move
           'top': (input_position.top + targetHeight) + 'px',
           'left': (input_position.left) + 'px'
         });
         $("#my-widget").fadeIn();
         $("#my-widget .my-widget-value").html(this.options.myvalue);
       }
     });

     $(document).on("mousedown";, this._hideWidget);
  },
  _generateHtml: function () {
    $("#my-widget").remove();
    $("body").append('<div id="my-widget">' + 
           '<button type="button" class="btn btn-info my-widget-minus">-</button>' + 
           '<p class="my-widget-value"></p>' + 
           '<button type="button" class="btn btn-info my-widget-plus">+</button>' +
           '</div>'
    );
    var that = this;
    // $("#my-widget .my-widget-plus").off("click");                
    // $("#my-widget .my-widget-minus").off("click");

    $("#my-widget .my-widget-plus").on("click", function () { 
      that.options.myvalue++;
      $(that.element).val(that.options.myvalue);
      $("#my-widget .my-widget-value").html(that.options.myvalue);
    });
 
    $("#my-widget .my-widget-minus").on("click", function () {
      that.options.myvalue--;
      $(that.element).val(that.options.myvalue);
      $("#my-widget .my-widget-value").html(that.options.myvalue);
    });
  },            
  _hideWidget: function () {
    var $target = $(event.target); 
    if (!$target.closest("#my-widget").length && !$target.hasClass("my-widget-input")) {
      $("#my-widget").fadeOut();
    }
  },
  _setOption: function (key, value) {
    if (key === "value") {
      value = this._constrain(value);
    }
    this._super(key, value);            
  },
  _setOptions: function (options) {                
    this._super(options);
    // this.refresh();
  },        
});

Options: These are the default options for the widget:

_create: The widget factory calls this method the first time the widget is initiated. This is used to create the initial DOM and attach any event handlers.

_create: It’s constructor method and it will be first method called for initialisation of widget.

_generateHtml: Called when you focus on your input text element. We have taken 2 buttons and 1 label. _hideWidget: function (): Called when you tap on window screen.

So here you can see in code we have used jquery .on(“click” , Its because we have tried to use same HTML for each widget initialised so that it doesn’t mess up generating HTML for each component.

Also please note down $(document).on(“mousedown”;, this._hideWidget);  to hide widget if clicked outside widget content.

How to use

<input id='txtbox1' class='txtInput' type='text'>
$("#txtbox1").mywidget({
  myvalue: 5
}); // Keep this in document.ready method

Summary

So it’s easy to create widget, its just about our vision and intensity to create individual jQuery component.

Of-course here is Github Link

Don’t miss the next post!

Loading

Related Posts