What are widgets in jQuery & how are they different from regular objects/functions?

Javascript has grown to be the most used programming language, for the web. It “gives life to a webpage”. But since Javascript is a very loosely-typed language, code quality and maintainability can turn out to be a huge issue.

Fortunately, people have come up with tools like requireJS and jQuery, to make coding in Javascript easier, by dividing your code in modules.

In this article, we’re going to discuss widgets in jQuery, a way to modularise our Javascript code, for most efficiency, scalability, and maintainability.

jQuery provides a way to bind certain functionalities to a particular element, so that instead of selecting the DOM element from within our function, we directly receive a reference to the DOM element, in which our widget was instantiated, inside our function. This concept is called widgets in jQuery and is useful in writing maintainable code, as well as instantiating multiple instances of the same widget, within different DOM elements.

Feel confused? Don’t worry. I did too, at the beginning. Let’s take a simple example to explain how widgets are useful.

Task

There are multiple DIVs, having data-urlattributes, containing URL of data, which we should fetch and display inside the DIV.

<div class="dynamic" data-url="http:://www.example.com/something"></div>
<div class="dynamic" data-url="http:://www.example.com/something-else"></div>
<div class="dynamic" data-url="http:://www.example.com/i-really-need-to-be-more-creative"></div>

Solution

Now in a normal situation, we would write some messy Javascript code like this

<script>
    var fetchData = function () {
        var selector = ".dynamic";
        var loadingHtml = "loading...";
        var elements = $(selector);
        elements.each(function (key, element) {
            element = $(element);
            $.ajax({
                url: element.data('url'),
                method: "GET",
                success: function (response) {
                    element.html(response);
                }
            });
        });
    };
    fetchData();
</script>

But using widgets, first we’ll develop a widget.

<script>
    $.widget('codilar.fetchData', {
        options: {
            loadingHtml: "Loading..."
        },
        _create: function () {
            var self = this;
            self.element.text(this.options.loadingHtml);
            $.ajax({
                url: self.element.data('url'),
                method: "GET",
                success: function (response) {
                    self.element.html(response);
                }
            });
        }
    });
</script>

And then we can call this widget on any DOM element, like this

$('.dynamic').fetchData();

So a widget is basically a JS object having 2 mandatory fields, options and _create. The _createfunction of your widget is called automatically, and the options object usually contains default configuration parameters for your widget, which can be overridden while calling the widget. Also, the this.elementfield is the current jQuery DOM element on which the widget is instantiated.

So since we’ve placed the loadingHtmlinside the options, we can override that while instantiating the widget, like this

$('.dynamic').fetchData({
    loadingHtml : "Widgeting..."
});

So that’s how you create, instantiate and modify a basic jQuery widget. Hope you liked this blog.

jquery

Additional resources

Magento jQuery widgets

jQuery widget coding standard

Previous tutorial

How to create a “HELLO WORLD” module in Magento 2?

Do let me know in the comment section below about what you want my next tutorial blog to be about. See you till next time!

Author



Leave a Reply

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

Recent Posts

Join 40,000+ Magento pros who receive eCommerce insights, tips, and best practices.

Request PWA Demo