Reputation: 597
I am learning how to make my own jQuery plugins and I'm running into an issue I am not sure why I am seeing. Here is my plugin:
(function($){
$.fn.clipping = function() {
console.log("Offset Width: " + this.offsetWidth);
console.log("Scroll Width: " + this.scrollWidth);
if(this.offsetWidth > this.scrollWidth) {
} else {
}
};
})( jQuery );
Then on document load I have this:
$("#tiles").clipping();
In the console I get this:
Offset Width: undefined
Scroll Width: undefined
Why is this happening? Do I need to do something to make sure it is looking at the exact element by ID that I want it to?
Upvotes: 0
Views: 77
Reputation: 33870
Inside you plugin, this
is a jQuery object. You should use .prop
to get DOM properties:
this.prop('offsetWidth');
this.prop('scrollWidth');
A good practice for plugins is to loop the initial jQuery object while returning it to allow chaining. Inside the loop, this
will be the DOM element.
(function($){
$.fn.clipping = function() {
return this.each(function(){
console.log("Offset Width: " + this.offsetWidth);
console.log("Scroll Width: " + this.scrollWidth);
if(this.offsetWidth > this.scrollWidth) {
} else {
}
});
};
})( jQuery );
And your plugin will work with object containing many DOM elements.
Upvotes: 1