Get Prefixed Method

Get a prefixed method from a scope. Checks for webkit, moz, ms, o by default. Use last param to change

by Aubrey Taylor

HTML

<p class="output"></p>

JavaScript

var getPrefixedMethod, scope, run, p, pclose;

// credits:
// Craig Butler: http://www.sitepoint.com/html5-full-screen-api/

p = '<p>';
pclose = '</p>';

getPrefixedMethod = function(scope, name, prefixes) {
        var prefixes, prefix, prefixableName, method, i, len;

        // creates a prefixable name by uppercasing first letter
        // e.g., 'fooBar' -> 'FooBar'
        prefixableName = name.substr(0,1).toUpperCase() + name.substr(1);
        prefixes = prefixes || ['webkit', 'moz', 'ms', 'o'];
        method = name;
        len = prefixes.length;
        i = 0;

        if(typeof scope[method] === 'function') {
            return scope[name];
        }

        for(i; i < len; i++) {
            prefix = prefixes[i];
            method = prefix + prefixableName;

            if(typeof scope[method] === 'function'){
                return scope[method];
            }
        }

        return false;
    }

scope = {
    foo: function(){},
    mozBar: function(){},
    webkitBaz: function(){},
    msQux: function(){},
    oDucks: function(){}
}

run = function() {
    var $output;
    
    $output = $('.output');
    
    if(getPrefixedMethod(scope, 'foo')){
        $output.append(p + 'found foo!' + pclose);
    }
    
    if(getPrefixedMethod(scope, 'bar')){
        $output.append(p + 'found bar!' + pclose);
    }
    
    if(getPrefixedMethod(scope, 'baz')){ 
        $output.append(p + 'found baz!' + pclose);
    }
   
    if(getPrefixedMethod(scope, 'qux')){
        $output.append(p + 'found qux!' + pclose);
    }
    
    if(getPrefixedMethod(scope, 'ducks')){
        $output.append(p + 'found ducks!' + pclose);
    }
    
    if(!getPrefixedMethod(scope, 'notinthere')){
        $output.append(p + 'notinthere did not exist, doh!' + pclose);
    }
}

run();