jquery watch {jquery detect attr change}

by bizamajig

HTML

<select>
    <option>1</option>
    <option>2</option>
</select>

<a href="#">disabled!</a>

JavaScript

// on click of the <a>, change the attr
$('a').click(function(e){
    e.preventDefault();
    
    if($(this).html() == 'disabled!')
    {
        $(this).html('enabled!');
        $('select').attr('disabled', 'disabled');
    }
    else
    {
        $(this).html('disabled!');
       $('select').removeAttr('disabled');
    }
    
});

// Function to watch for attribute changes
// http://darcyclarke.me/development/detect-attribute-changes-with-jquery
$.fn.watch = function(props, callback, timeout){
    if(!timeout)
        timeout = 10;
    return this.each(function(){
        var el         = $(this),
            func     = function(){ __check.call(this, el) },
            data     = {    props:     props.split(","),
                        func:     callback,
                        vals:     [] };
        $.each(data.props, function(i) { data.vals[i] = el.attr(data.props[i]); });
        el.data(data);
        if (typeof (this.onpropertychange) == "object"){
            el.bind("propertychange", callback);
        } else if ($.browser.mozilla){
            el.bind("DOMAttrModified", callback);
        } else {
            setInterval(func, timeout);
        }
    });
    function __check(el) {
        var data     = el.data(),
            changed = false,
            temp    = "";
        for(var i=0;i < data.props.length; i++) {
            temp = el.attr(data.props[i]);
            if(data.vals[i] != temp){
                data.vals[i] = temp;
                changed = true;
                break;
            }
        }
        if(changed && data.func) {
            data.func.call(el, data);
        }
    }
}

// What do we want to watch
$('select').watch('disabled', function(){
alert('changed');
});