jqueryjquery-widgets

How to write a jQuery widget to add 'Hello world' to the selected div


I need some help writing a jQuery widget.

As an exercise, I am trying to create a widget which adds a 'Hello World' message to the selected element when the page is loaded.

The below code should append "Hello World" to div with class "123", but nothing happens. Can anyone see what I did wrong?

jQuery/javascript:

$.widget("custom.hwLoader",{

    options: { 
    clear:null
    },

    _create: function() {
        this.element;
        this.name; 
        this.namespace; 
        this.element.on("load"+this.eventNamespace,
            function(){
                $("<h1>Hello World</h1>").appendTo(this.element);
            }
        )
    },

    _setOption: function( key, value ) {

        this._super("_setOption", key, value );
    },

    _destroy: function() {
        this.element.unbind('.'+this.eventNamespace);
    }

});

HTML:

$("<div  class='addHere'></div>").appendTo("body");
$(".addHere").hwLoader();

Solution

  • You can use jQuery text method: http://api.jquery.com/text/

    $(document).ready(function(){
        $('#selected_element').text('Hello World');
    });
    

    Here's a fiddle: http://jsfiddle.net/7zq2kvw0/1/

    and it's safer to start a class or id name with a letter (see this question: What are valid values for the id attribute in HTML?)

    With a widget:

    Widget factory is a jQuery UI functionality. A simple function woud be much more adapted for this usage. If you really want to use a widget, make sure you link both jQuery and jQuery UI scripts on your page:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
    

    In this case, the simple following code works well:

    $.widget("custom.HW_Loader",{
        _create: function() {
            this.element.text('Hello World');
        }
    });
    

    And you can call the widget with $('#element').HW_Loader();

    Here in action: http://jsfiddle.net/7zq2kvw0/3/