Home > Software design >  JQuery Widget Factory, use options to set widget on webpage
JQuery Widget Factory, use options to set widget on webpage

Time:09-16

I am still a newbie at JavaScript and don't have years of experience using JavaScript on Web Development. JavaScript is very messy considering nesting of functions and sometimes objects and things like passing function calls as a variable.

My HTML has a div tag to contain a JQuery widget.

HTML:

<div id="slide"></div>

The slider displays as per normal but it is not done with the options set with the widget factory. The lab requirement is such that I must use widget factory.

JavaScript

// slider with widget factory
$(document).ready(function()
{
    $(function() {
        $.widget("custom.slider",{
            options: {
                value: 50,
                max: 175,
                min: 1,
                orientation: "vertical",
    
                // Callbacks
                change: null,
                log: null
            },
            _create: function () {
                this.options.value;
                this.options.max;
                this.options.min;
                this.options.orientation;
            }
        });
    });
    $("#slide").slider();
});

I noticed JavaScript has a lot of programming concepts that I have never faced before compared to the usual programming languages. So the learning curve steepens exponentially.

CodePudding user response:

Consider the following.

$(function() {
  $.widget("custom.mySlide", $.ui.slider, {
    options: {
      value: 50,
      max: 175,
      min: 1,
      orientation: "vertical"
    }
  });

  $("#slide").mySlide();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<div id="slide"></div>

This creates a Custom Widget based on $.ui.slider and sets default Options.

Please be aware that $(document).ready(function(){ }); and $(function(){ }); perform the same thing, so do not use both, use one or the other. They both cause the script to wait until the Document is ready.

You do not want to overwrite _create function.

The _create() method is the widget's constructor. There are no parameters, but this.element and this.options are already set.

See More: https://api.jqueryui.com/jQuery.widget/#method-_create

  • Related