Retrofitting jQuery prop() for when using both older and newer jQuery versions

When upgrading your existing website to jQuery 1.6 or higher, you may have noticed that the attr() method stopped working like it has since time immemorial, breaking all previous code that used it. Supposedly jQuery 1.61 added some backwards compatibility fixes, but they don’t really work, at least for me. They say “just replace all attr() calls for prop() and be done”, however it’s not that simple if your code is supposed to work on different versions of jQuery, for example when developing extensions or modules for constantly updated frameworks, since prop() didn’t exist before jQuery 1.6. Actually, there is a simple way to make your code work on both older and newer jQuery versions. All you need to do is replace all attr() calls for prop() (it takes the same arguments so don’t worry), and add the following before your code:

       if (typeof jQuery.fn.prop != 'function') {
            jQuery.fn.prop = jQuery.fn.attr;
        }
    

All this does is check if the prop() method exists, and if not, it creates it by cloning attr(). Hope this saves you some time.

Leave a Reply

Your email address will not be published. Required fields are marked *