Question

jQuery.widget("ui.test", {
    _init: function(){
        alert(this.element.innerHTML);
    }

});

How do I make it so when I am attaching this to a HTML element
It will alert the innerHTML (I know it does nothing, it is just to understand the basics).

<div id="baba">ja jaj</div>
<script>
$('#baba').test();//will alert "ja jaj"
</script>

What am I missing here?

What I missed:

My code was actually perfectly fine, EXCEPT, I assumed that this.element is an HTML element, while in reality it is a jQuery object. Hence innerHTML did nothing while html(), in the answer below, worked.

Was it helpful?

Solution

You're missing the jQuery UI library. Simply attach it and yu're good to go - http://jsfiddle.net/jUm5H/

(function($) {
    $.widget("ui.test", {
        _init: function() {
            alert( this.element.html() );
        }
    });
}(jQuery));

$('#baba').test();

UPDATE

"To make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to an IIFE (Immediately Invoked Function Expression) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution." - source

So it's basically just a good practice. You can ignore it and it will work - http://jsfiddle.net/jUm5H/1/ But it's better to do it in a correct way from the beginning. It might save a lot of debugging time and frustration in the future projects :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top