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

13 Nov 2018
Jquery Widgets

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.

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!

Was this article helpful?
Arijit Panigrahi

Arijit Panigrahi

I am experienced in Magento development specialising in PHP, HTML, jQuery, and PWA projects with expertise in GraphQL, algorithm design, and database design, I have delivered high-quality solutions for diverse clients. I am experienced in algorithm design, optimizing application performance, and database efficiency. With a commitment to professionalism and a passion for continuous learning, remain at the forefront of web development innovation.

Our Offices Are Here

India flag

India

7th Floor, Jupiter Block Prestige Tech Park, Kadubeesanahalli, Bellandur Amtankere, Bengaluru, Karnataka 560103

+91 888 49 00 505

UAE flag

UAE

DTECH, Techno Hub 1, Dubai Silicon Oasis Authority, United Arab Emirates - Dubai - United Arab Emirates

+971 55 557 8583

Saudi Arabia flag

Saudi Arabia

Building No 6827, Prince Turki Ibn Abdulaziz Al Awal Street, Al Muhammadiyah District, Riyadh, Kingdom of Saudi Arabia- 12362

+966 50 809 6356

Oman flag

Oman

Building No. 2/786, Way No. 43, Block No. 336, Al Khud 132, Muscat, Oman

+968 7694 6200

Singapore flag

Singapore

Codilar Digital Pte Ltd, 68 Circular Road, #02-01, 049422, Singapore

Indonesia flag

Indonesia

Satrio Tower, Floor 6, Unit C and D, Desa/Kelurahan Kuningan Timur, Kec. Setiabudi, Kota Adm. Jakarta Selatan, Provinsi DKI Jakarta

CONTACT US

Let's Do Something Great Together

We look forward to hearing from you

REGIONS

KSA|UAE|OMAN|INDIA|SINGAPORE|INDONESIA