YUI recommends YUI3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

This documentation is no longer maintained.

YUI 2: YAHOO Global Object

YUI 2: YAHOO Global Object

The YAHOO Global Object provides a single global namespace within which all YUI Library code resides. It must be included on every page that utilizes the YUI Library, and it must appear before any of the other YUI component.

The YAHOO Global Object also contains a number of methods that are used throughout the library.

Getting Started

The YAHOO Global Object must be included before any of the other script files that are part of YUI:

  1. <!-- YAHOO Global Object source file -->
  2. <script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
  3.  
  4. <!-- Additional source files go here -->
  5.  
<!-- YAHOO Global Object source file -->
<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
 
<!-- Additional source files go here -->
 

YUI dependency configurator.

YUI Dependency Configurator:

Instead of copying and pasting the filepaths above, try letting the YUI dependency Configurator determine the optimal file list for your desired components; the Configurator uses YUI Loader to write out the full HTML for including the precise files you need for your implementation.

Note: If you are loading components via the YUI Loader, this component is included in the YUI Loader package — you do not need to load it separately. If YUI Loader is on the page, so is the YAHOO Global Object.

Where these files come from: The files included using the text above will be served from Yahoo! servers. JavaScript files are minified, meaning that comments and white space have been removed to make them more efficient to download. To use the full, commented versions or the -debug versions of YUI JavaScript files, please download the library distribution and host the files on your own server.

Order matters: As is the case generally with JavaScript and CSS, order matters; these files should be included in the order specified above. If you include files in the wrong order, errors may result.

Using the Utility Methods in YAHOO

YAHOO.namespace

The YAHOO Object automatically generates namespaces for YAHOO.util, YAHOO.widget, YAHOO.env, YAHOO.tool, and YAHOO.example. These namespaces are reserved for script that is included in the YUI release. Additional namespaces can be created to contain custom applications built upon the library:

  1. // Creates a namespace for "myproduct1"
  2. YAHOO.namespace("myproduct1");
  3. YAHOO.myproduct1.Class1 = function(info) {
  4. alert(info);
  5. };
  6.  
  7. // Creates a namespace for "myproduct2", and for "mysubproject1"
  8. YAHOO.namespace("myproduct2.mysubproject1");
  9. YAHOO.myproduct2.mysubproject1.Class1 = function(info) {
  10. alert(info);
  11. };
  12.  
// Creates a namespace for "myproduct1"
YAHOO.namespace("myproduct1");
YAHOO.myproduct1.Class1 = function(info) {
    alert(info);
};
 
// Creates a namespace for "myproduct2", and for "mysubproject1"
YAHOO.namespace("myproduct2.mysubproject1");
YAHOO.myproduct2.mysubproject1.Class1 = function(info) {
    alert(info);
};
 

YAHOO.lang

YAHOO.lang contains javascript language utilities and extensions that are used in the YUI library.

  1. // true, an array literal is an array
  2. YAHOO.lang.isArray([1, 2]);
  3.  
  4. // false, an object literal is not an array
  5. YAHOO.lang.isArray({"one": "two"});
  6.  
  7. // however, when declared as an array, it is true
  8. function() {
  9. var a = new Array();
  10. a["one"] = "two";
  11. return YAHOO.lang.isArray(a);
  12. }();
  13.  
  14. // false, a collection of elements is like an array, but isn't
  15. YAHOO.lang.isArray(document.getElementsByTagName("body"));
  16.  
  17. // true, false is a boolean
  18. YAHOO.lang.isBoolean(false);
  19.  
  20. // false, 1 and the string "true" are not booleans
  21. YAHOO.lang.isBoolean(1);
  22. YAHOO.lang.isBoolean("true");
  23.  
  24. // null is null, but false, undefined and "" are not
  25. YAHOO.lang.isNull(null); // true
  26. YAHOO.lang.isNull(undefined); // false
  27. YAHOO.lang.isNull(""); // false
  28.  
  29. // a function is a function, but an object is not
  30. YAHOO.lang.isFunction(function(){}); // true
  31. YAHOO.lang.isFunction({foo: "bar"}); // false
  32.  
  33. // true, ints and floats are numbers
  34. YAHOO.lang.isNumber(0);
  35. YAHOO.lang.isNumber(123.123);
  36.  
  37. // false, strings that can be cast to numbers aren't really numbers
  38. YAHOO.lang.isNumber("123.123");
  39.  
  40. // false, undefined numbers and infinity are not numbers we want to use
  41. YAHOO.lang.isNumber(1/0);
  42.  
  43. // true, objects, functions, and arrays are objects
  44. YAHOO.lang.isObject({});
  45. YAHOO.lang.isObject(function(){});
  46. YAHOO.lang.isObject([1,2]);
  47.  
  48. // false, primitives are not objects
  49. YAHOO.lang.isObject(1);
  50. YAHOO.lang.isObject(true);
  51. YAHOO.lang.isObject("{}");
  52.  
  53. // strings
  54. YAHOO.lang.isString("{}"); // true
  55. YAHOO.lang.isString({foo: "bar"}); // false
  56. YAHOO.lang.isString(123); // false
  57. YAHOO.lang.isString(true); // false
  58.  
  59. // undefined is undefined, but null and false are not
  60. YAHOO.lang.isUndefined(undefined); // true
  61. YAHOO.lang.isUndefined(false); // false
  62. YAHOO.lang.isUndefined(null); // false
  63.  
// true, an array literal is an array
YAHOO.lang.isArray([1, 2]);
 
// false, an object literal is not an array
YAHOO.lang.isArray({"one": "two"});
 
// however, when declared as an array, it is true
function() {
    var a = new Array();
    a["one"] = "two";
    return YAHOO.lang.isArray(a);
}();
 
// false, a collection of elements is like an array, but isn't
YAHOO.lang.isArray(document.getElementsByTagName("body"));
 
// true, false is a boolean
YAHOO.lang.isBoolean(false);
 
// false, 1 and the string "true" are not booleans
YAHOO.lang.isBoolean(1);
YAHOO.lang.isBoolean("true");
 
// null is null, but false, undefined and "" are not
YAHOO.lang.isNull(null); // true
YAHOO.lang.isNull(undefined); // false
YAHOO.lang.isNull(""); // false
 
// a function is a function, but an object is not
YAHOO.lang.isFunction(function(){}); // true
YAHOO.lang.isFunction({foo: "bar"}); // false
 
// true, ints and floats are numbers
YAHOO.lang.isNumber(0);
YAHOO.lang.isNumber(123.123);
 
// false, strings that can be cast to numbers aren't really numbers
YAHOO.lang.isNumber("123.123");
 
// false, undefined numbers and infinity are not numbers we want to use
YAHOO.lang.isNumber(1/0);
 
// true, objects, functions, and arrays are objects
YAHOO.lang.isObject({});
YAHOO.lang.isObject(function(){});
YAHOO.lang.isObject([1,2]);
 
// false, primitives are not objects
YAHOO.lang.isObject(1);
YAHOO.lang.isObject(true);
YAHOO.lang.isObject("{}");
 
// strings
YAHOO.lang.isString("{}"); // true
YAHOO.lang.isString({foo: "bar"}); // false
YAHOO.lang.isString(123); // false
YAHOO.lang.isString(true); // false
 
// undefined is undefined, but null and false are not
YAHOO.lang.isUndefined(undefined); // true
YAHOO.lang.isUndefined(false); // false
YAHOO.lang.isUndefined(null); // false
 

YAHOO.lang.hasOwnProperty

YAHOO.lang.hasOwnProperty can be used to filter out properties that were added to the Object prototype when iterating over an object that is being used as a hash table. This feature is natively supported across all current A-Grade browsers, but it wasn't added to Safari until recently; all internal usage of the hasOwnProperty test within YUI will use the version in YAHOO.lang for the forseeable future, and we recommend that you do the same in your own implementations. YAHOO.lang.hasOwnProperty will use the native browser function unless it isn't available.

  1. // this is what we are protecting against
  2. Object.prototype.myCustomFunction = function(x) {
  3. alert(x);
  4. }
  5.  
  6. var o = {};
  7. o["foo"] = "bar";
  8. o["marco"] = "polo";
  9.  
  10. // this is where we need the protection
  11. for (var i in o) {
  12. if (YAHOO.lang.hasOwnProperty(o, i)) {
  13. alert("good key: " + i);
  14. } else {
  15. alert("bad key: " + i);
  16. }
  17. }
  18.  
// this is what we are protecting against
Object.prototype.myCustomFunction = function(x) {
    alert(x);
}
 
var o = {};
o["foo"] = "bar";
o["marco"] = "polo";
 
// this is where we need the protection
for (var i in o) {
    if (YAHOO.lang.hasOwnProperty(o, i)) {
        alert("good key: " + i);
    } else {
        alert("bad key: " + i);
    }
}
 

YAHOO.lang.extend

YAHOO.lang.extend provides a simple mechanism for setting up the prototype, constructor, and superclass properties for objects that are extending other objects. It also prevents the constructor of the extended object (ie, the superclass) from being executed twice. YAHOO.lang.extend was relocated into the YAHOO.lang package in version 2.9.0. YAHOO.extend is a deprecated alias for YAHOO.lang.extend.

  1. YAHOO.namespace("test");
  2.  
  3. YAHOO.test.Class1 = function(info) {
  4. alert("Class1: " + info);
  5. };
  6.  
  7. YAHOO.test.Class1.prototype.testMethod = function(info) {
  8. alert("Class1: " + info);
  9. };
  10.  
  11. YAHOO.test.Class2 = function(info) {
  12. // chain the constructors
  13. YAHOO.test.Class2.superclass.constructor.call(this, info);
  14. alert("Class2: " + info);
  15. };
  16.  
  17. // Class2 extends Class1. Must be done immediately after the Class2 constructor
  18. YAHOO.lang.extend(YAHOO.test.Class2, YAHOO.test.Class1);
  19.  
  20. YAHOO.test.Class2.prototype.testMethod = function(info) {
  21. // chain the method
  22. YAHOO.test.Class2.superclass.testMethod.call(this, info);
  23. alert("Class2: " + info);
  24. };
  25.  
  26. var class2Instance = new YAHOO.test.Class2("constructor executed");
  27. class2Instance.testMethod("testMethod invoked");
  28.  
YAHOO.namespace("test");
 
YAHOO.test.Class1 = function(info) {
    alert("Class1: " + info);
};
 
YAHOO.test.Class1.prototype.testMethod = function(info) {
    alert("Class1: " + info);
};
 
YAHOO.test.Class2 = function(info) {
    // chain the constructors
    YAHOO.test.Class2.superclass.constructor.call(this, info);
    alert("Class2: " + info);
};
 
// Class2 extends Class1.  Must be done immediately after the Class2 constructor
YAHOO.lang.extend(YAHOO.test.Class2, YAHOO.test.Class1);
 
YAHOO.test.Class2.prototype.testMethod = function(info) {
    // chain the method
    YAHOO.test.Class2.superclass.testMethod.call(this, info);
    alert("Class2: " + info);
};
 
var class2Instance = new YAHOO.test.Class2("constructor executed");
class2Instance.testMethod("testMethod invoked");
 

YAHOO.lang.augment

YAHOO.lang.augment provides a way to reuse code by applying some or all of the prototype properties in one object to another object. YAHOO.augment is a deprecated alias for YAHOO.lang.augment.

  1. <!-- debugger output for environments without "console" -->
  2. <div id="consoleelement">&nbsp;</div>
  3.  
<!-- debugger output for environments without "console" -->
<div id="consoleelement">&nbsp;</div>
 
  1. ////////////////////////////////////////////////////////////////////////////
  2. // The ConsoleProvider example will log to the console if available, or a
  3. // div with id="consoleelement" if the console is not available
  4. ////////////////////////////////////////////////////////////////////////////
  5. YAHOO.example.ConsoleProvider = function() { };
  6. YAHOO.example.ConsoleProvider.prototype = {
  7. log: function(msg) {
  8. // use the error console if available (FF+FireBug or Safari)
  9. if (typeof console != "undefined") {
  10. console.log(msg);
  11. // write the msg to a well-known div element
  12. } else {
  13. var el = document.getElementById("consoleelement");
  14. if (el) {
  15. el.innerHTML += "<p>" + msg + "</p>";
  16. }
  17. }
  18. }
  19. };
  20.  
  21. ////////////////////////////////////////////////////////////////////////////
  22. // Define a class that should be able to write debug messages
  23. ////////////////////////////////////////////////////////////////////////////
  24. YAHOO.example.ClassWithLogging = function() { };
  25. YAHOO.lang.augment(YAHOO.example.ClassWithLogging, YAHOO.example.ConsoleProvider);
  26.  
  27. ////////////////////////////////////////////////////////////////////////////
  28. // Try it out
  29. ////////////////////////////////////////////////////////////////////////////
  30. var c = new YAHOO.example.ClassWithLogging();
  31. c.log("worked");
  32.  
  33.  
////////////////////////////////////////////////////////////////////////////
// The ConsoleProvider example will log to the console if available, or a 
// div with id="consoleelement" if the console is not available
////////////////////////////////////////////////////////////////////////////
YAHOO.example.ConsoleProvider = function() { };
YAHOO.example.ConsoleProvider.prototype = {
    log: function(msg) {
        // use the error console if available (FF+FireBug or Safari)
        if (typeof console != "undefined") {
            console.log(msg);
        // write the msg to a well-known div element
        } else {
            var el = document.getElementById("consoleelement");
            if (el) {
                el.innerHTML += "<p>" + msg + "</p>";
            }
        }
    }
};
 
////////////////////////////////////////////////////////////////////////////
// Define a class that should be able to write debug messages
////////////////////////////////////////////////////////////////////////////
YAHOO.example.ClassWithLogging = function() { };
YAHOO.lang.augment(YAHOO.example.ClassWithLogging, YAHOO.example.ConsoleProvider);
 
////////////////////////////////////////////////////////////////////////////
// Try it out
////////////////////////////////////////////////////////////////////////////
var c = new YAHOO.example.ClassWithLogging();
c.log("worked");
 
 

YAHOO.log

YAHOO.log is included in the Yahoo Global Object so that logging code can be included anywhere in YUI code (or in your own code) even if the YUI Logger Control is not on the page; this prevents errors from appearing as you begin removing debugging instrumentation from your project. YAHOO.log executes YAHOO.widget.Logger.log if the Logger Control is available; otherwise, it does nothing. See the documentation for the Logger Control for more information about how to make use of it in your work.

  1. YAHOO.namespace("test");
  2.  
  3. YAHOO.test.Class1 = function(info) {
  4. YAHOO.log("Class1: " + info, "error", "Class1");
  5. };
  6.  
YAHOO.namespace("test");
 
YAHOO.test.Class1 = function(info) {
    YAHOO.log("Class1: " + info, "error", "Class1");
};
 

YAHOO_config and YAHOO.env

YAHOO.env contains information the browsing environment. In particular, it contains information about all of the YUI components that have been loaded on the page. This data is accessible by any component by using YAHOO.env.getVersion, but it is especially useful for environments where the library is dynamically loaded.

Instead of using polling techniques to determine when YAHOO and the rest of the YUI Library is loaded, you can define within YAHOO_config a callback method that will be invoked every time a new YUI module is inserted into the page. Your callback method, defined as YAHOO_config.listener, will receive as an argument an information object containing the following information:

property type description
name string The name of the YUI component that has just loaded. The name is an arbitrary string corresponding to a YUI component. Current YUI component names can be found in the YUI Module Names section below.
version string The version in use (e.g., "2.9.0").
build number The build number of the current version. This is a continuously incremented integer that will grow larger with each version of the library.
versions array An array containing the string version information for all versions of this component that have been registered during the current page session. This can help identify issues that were the result of multiple versions of a module on the page.
builds array An array containing the numeric build information for all versions of this component that have been registered during the current page session.
mainClass object The principal object/class for the registered component. This object will have been stamped with its current version and build information. If mainClass.VERSION != version or mainClass.BUILD != build, multiple versions of pieces of the library have been loaded, potentially causing issues.

In the extended code sample below, the YAHOO_config object is used to register a listener that fires when YUI components are loaded:

  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4.  
  5. // will be called each time a module is loaded
  6. function mycallback(info) {
  7.  
  8. // see the table in the documentation above for
  9. // the contents of the info object passed in here
  10. // as your argument.
  11.  
  12. alert(info.name + " loaded");
  13.  
  14. // once the logger is on the page we can get to work
  15. if (info.name == "logger") {
  16. YAHOO.widget.Logger.enableBrowserConsole()
  17. var l = new YAHOO.widget.LogWriter("(");
  18.  
  19. YAHOO.example.EnvTest = function() {
  20. function log(msg,cat) {
  21. var c=c||"info";
  22. YAHOO.log(msg,c,"LangTest");
  23. }
  24.  
  25. return {
  26. init: function() {
  27. new YAHOO.widget.LogReader("logoutput");
  28. log("init");
  29. },
  30.  
  31. showInfo: function(e, module){
  32. // YAHOO.env.getVersion returns the same data
  33. // object that YAHOO_config.listener receives
  34. var info = YAHOO.env.getVersion(module);
  35.  
  36. log("name: " + info.name);
  37. log("version: " + info.version);
  38. log("build: " + info.build);
  39. log("versions: " + info.versions);
  40. log("builds: " + info.builds);
  41. log("mainClass version: " + info.mainClass.VERSION);
  42. }
  43. };
  44. } ();
  45.  
  46. YAHOO.util.Event.addListener(window, "load", YAHOO.example.EnvTest.init);
  47. YAHOO.util.Event.addListener("showeventbutton", "click", YAHOO.example.EnvTest.showInfo, "event");
  48. }
  49. }
  50.  
  51. YAHOO_config = {
  52. listener: mycallback
  53. };
  54.  
  55. </script>
  56. <script src = "../src/js/YAHOO.js" ></script>
  57. <script src = "http://yui.yahooapis.com/2.9.0/build/event/event.js" ></script>
  58. <script src = "http://yui.yahooapis.com/2.9.0/build/dom/dom.js" ></script>
  59. <script src = "http://yui.yahooapis.com/2.9.0/build/dragdrop/dragdrop.js" ></script>
  60. <script src = "http://yui.yahooapis.com/2.9.0/build/logger/logger.js" ></script>
  61. <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/logger/assets/logger.css">
  62. <style> #logoutput {float: right}</style>
  63. </head>
  64. <body>
  65. <input type="button" id="showeventbutton" value="show event version" />
  66. <div id="logoutput"></div>
  67. </body>
  68. </html>
  69.  
<html>
<head>
<script type="text/javascript">
 
// will be called each time a module is loaded
function mycallback(info) {
 
    // see the table in the documentation above for
	// the contents of the info object passed in here
	// as your argument.
 
    alert(info.name + " loaded");
 
    // once the logger is on the page we can get to work
    if (info.name == "logger") {
        YAHOO.widget.Logger.enableBrowserConsole()
        var l = new YAHOO.widget.LogWriter("(");
 
        YAHOO.example.EnvTest = function() {
            function log(msg,cat) {
                var c=c||"info";
                YAHOO.log(msg,c,"LangTest");
            }
 
            return {
                init: function() {
                    new YAHOO.widget.LogReader("logoutput");
                    log("init");
                },
 
                showInfo: function(e, module){
                    // YAHOO.env.getVersion returns the same data
                    // object that YAHOO_config.listener receives
                    var info = YAHOO.env.getVersion(module);
 
                    log("name: " + info.name);
                    log("version: " + info.version);
                    log("build: " + info.build);
                    log("versions: " + info.versions);
                    log("builds: " + info.builds);
                    log("mainClass version: " + info.mainClass.VERSION);
                }
            };
        } ();
 
        YAHOO.util.Event.addListener(window, "load", YAHOO.example.EnvTest.init);
        YAHOO.util.Event.addListener("showeventbutton", "click", YAHOO.example.EnvTest.showInfo, "event");
    }
}
 
YAHOO_config = {
    listener: mycallback
};
 
</script>
<script src = "../src/js/YAHOO.js" ></script>
<script src = "http://yui.yahooapis.com/2.9.0/build/event/event.js" ></script>
<script src = "http://yui.yahooapis.com/2.9.0/build/dom/dom.js" ></script>
<script src = "http://yui.yahooapis.com/2.9.0/build/dragdrop/dragdrop.js" ></script>
<script src = "http://yui.yahooapis.com/2.9.0/build/logger/logger.js" ></script>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/logger/assets/logger.css">
<style> #logoutput {float: right}</style>
</head>
<body>
<input type="button" id="showeventbutton" value="show event version" />
<div id="logoutput"></div>
</body>
</html>
 

YUI Module Names

Each YUI component has a corresponding module name that is used as a unique identifier within YUI scripts. For example, the Event Utility is internally referred to as "event". The Yahoo Global Object and other components (such as the YUILoader Utility) make use of these unique module names. Here is the full list of YUI module names.

YUI on Mobile: Using YAHOO Global Object with "A-Grade" Mobile Browsers

About this Section: YUI generally works well with mobile browsers that are based on A-Grade browser foundations. For example, Nokia's N-series phones, including the N95, use a browser based on Webkit — the same foundation shared by Apple's Safari browser, which is found on the iPhone. The fundamental challenges in developing for this emerging class of full, A-Grade-derived browsers on handheld devices are:

  • Screen size: You have a much smaller canvas;
  • Input devices: Mobile devices generally do not have mouse input, and therefore are missing some or all mouse events (like mouseover);
  • Processor power: Mobile devices have slower processors that can more easily be saturated by JavaScript and DOM interactions — and processor usage affects things like battery life in ways that don't have analogues in desktop browsers;
  • Latency: Most mobile devices have a much higher latency on the network than do terrestrially networked PCs; this can make pages with many script, css or other types of external files load much more slowly.

There are other considerations, many of them device/browser specific (for example, current versions of the iPhone's Safari browser do not support Flash). The goal of these sections on YUI User's Guides is to provide you some preliminary insights about how specific components perform on this emerging class of mobile devices. Although we have not done exhaustive testing, and although these browsers are revving quickly and present a moving target, our goal is to provide some early, provisional advice to help you get started as you contemplate how your YUI-based application will render in the mobile world.

More Information:

The YAHOO global works without known issues in tested mobile environments. In a future release of the library, YAHOO.env.ua will be expanded to include detection for certain "A-Grade" mobile browsers. Until then, you can use the following code to detect a number of interesting mobile browsers:

  1. var mobile = false, ua = navigator.userAgent, m;
  2.  
  3. if (YAHOO.env.ua.webkit) {
  4. if (/ Mobile\//.test(ua)) {
  5. mobile = "iPhone";
  6. } else {
  7. m=ua.match(/NokiaN[^\/]*/);
  8. if (m) {
  9. mobile = m[0]; // Nokia N-series, ex: NokiaN95
  10. }
  11. }
  12. } else if (YAHOO.env.ua.opera) {
  13. m=ua.match(/Opera Mini[^;]*/);
  14. if (m) {
  15. mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
  16. }
  17. }
  18.  
  19. if (!mobile) {
  20. // code here won't execute in the detected mobile browsers
  21. }
  22.  
var mobile = false, ua = navigator.userAgent, m;
 
if (YAHOO.env.ua.webkit) {
    if (/ Mobile\//.test(ua)) {
        mobile = "iPhone";
    } else {
        m=ua.match(/NokiaN[^\/]*/);
        if (m) {
            mobile = m[0]; // Nokia N-series, ex: NokiaN95
        }
    }
} else if (YAHOO.env.ua.opera) {
    m=ua.match(/Opera Mini[^;]*/);
    if (m) {
        mobile = m[0]; // ex: Opera Mini/2.0.4509/1316
    }
}
 
if (!mobile) {
    // code here won't execute in the detected mobile browsers
}
 

Support & Community

The YUI Library and related topics are discussed on the on the YUILibrary.com forums.

Also be sure to check out YUIBlog for updates and articles about the YUI Library written by the library's developers.

Filing Bugs & Feature Requests

The YUI Library's public bug tracking and feature request repositories are located on the YUILibrary.com site. Before filing new feature requests or bug reports, please review our reporting guidelines.

Copyright © 2013 Yahoo! Inc. All rights reserved.

Privacy Policy - Copyright Policy - Job Openings