0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.