Google Closure cheat sheet
Write next code in your <head>:
// local path
<script type="text/javascript" src="js/closure/goog/base.js"></script>
Google Closure CDN
Closure Library differs from a lot of other JavaScript libraries in that it's very broad and large and, in general,
every class or namespace is stored in its own file, so just what is needed can be included in an app. As such,
it's infeasible to require users to pull all of Closure as they would another library in the AJAX APIs,
as the download would be very large and split over a lot of individual requests. So we don't have any immediate
plans for AJAX API support.
Open Closure Compiler, and configure your requirements:
// ==ClosureCompiler==
// @output_file_name default.js
// @compilation_level SIMPLE_OPTIMIZATIONS
// @use_closure_library true
// ==/ClosureCompiler==
goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');
Require
goog.require('goog.dom');
// Dojo third-party
goog.require('goog.dom.query');
Examples
Return element with id="header":
goog.dom.getElement('header')
// or
goog.dom.$('header')
Return first element with class="myclass":
goog.dom.getElementByClass('myclass')
Return all elements with class="myclass":
goog.dom.getElementsByClass('myclass')
Usage getElementsByTagNameAndClass:
// return all DOM elements
goog.dom.getElementsByTagNameAndClass()
// return <p> elements with class="myclass"
goog.dom.getElementsByTagNameAndClass('p','myclass')
// or
goog.dom.$$('p','myclass')
// return <div> elements without class
goog.dom.$$('div')
// return all elements with class="myclass"
goog.dom.$$(null, 'myclass')
// return <div> elements with class="myclass" in element with id="id"
goog.dom.$$('div', 'myclass', goog.dom.$('id'))
Usage goog.dom.getAncestorByTagNameAndClass:
// all parent elements
goog.dom.getAncestorByTagNameAndClass(goog.dom.$('id'))
// all parent DIV's
goog.dom.getAncestorByTagNameAndClass(goog.dom.$('id'), 'div')
// all parent elements with class="myclass"
goog.dom.getAncestorByTagNameAndClass(goog.dom.$('id'), null, 'myclass')
// all parent DIV's with class="myclass"
goog.dom.getAncestorByTagNameAndClass(goog.dom.$('id'), 'div', 'myclass')
Return all elements from query:
goog.dom.query('h1+h2, a:last-child')
Require
goog.require('goog.dom');
Examples
Create DOM Element:
var div = goog.dom.createDom(
'div', // element
{ // properties
'id':'myId',
'class':'myClassName'
'style':'color:red;font-size:18px;'
},
'Hello World' // content - text or elements
);
// or
var div = goog.dom.$dom(
'div',
{
'id':'myId',
'class':'myClassName'
'style':'color:red;font-size:18px;'
},
'Hello World'
);
Sets multiple properties:
goog.dom.setProperties(goog.dom.$('id'), {
'class':'myClass',
'style':'color:red;border:4px solid black'
})
Append childs:
goog.dom.appendChild(goog.dom.$('id'), goog.dom.$dom('p'));
Require
goog.require('goog.dom.classes');
Examples
Sets the entire class name(s) of an element:
goog.dom.classes.set(goog.dom.$('id'), 'className')
Gets an array of class names on an element
goog.dom.classes.get(goog.dom.$('id'))
Adds a class or classes to an element:
goog.dom.classes.add(goog.dom.$('id'), 'className', 'anotherClass')
Removes a class or classes from an element:
goog.dom.classes.remove(goog.dom.$('id'), 'className', 'anotherClass')
Switches a class on an element from one to another:
goog.dom.classes.swap(goog.dom.$('id'), 'fromClass', 'toClass')
Adds zero or more classes to an element and removes zero or more:
goog.dom.classes.addRemove(goog.dom.$('id'), 'addClass', ['removeClass'])
Returns true if an element has a class:
goog.dom.classes.has(goog.dom.$('id'), 'className')
Adds or removes a class depending on the enabled argument:
goog.dom.classes.enable(goog.dom.$('id'), 'className', true||false)
Removes a class if an element has it, and adds it the element doesn't have it:
goog.dom.classes.toggle(goog.dom.$('id'), 'className')
Require
goog.require('goog.style');
Examples
Retrieves an explicitly-set style value of a node:
goog.style.getStyle(goog.dom.$('id'), 'color')
Sets a style value on an element:
goog.style.setStyle(goog.dom.$('id'), 'color', '#ffff00')
// or
goog.style.setStyle(goog.dom.$('id'), {
'margin-top':'20px',
'margin-bottom':'20px'
})
Element size manipulation:
// gets the height and width
goog.style.getSize(goog.dom.$('id'))
// sets the height and width
goog.style.setSize(goog.dom.$('id'), width, height)
// or
goog.style.setSize(goog.dom.$('id'), new goog.math.Size(width, height))
// sets the height
goog.style.setHeight(goog.dom.$('id'), height)
// sets the width
goog.style.setWidth(goog.dom.$('id'), width)
Element position:
// sets the top/left values of an element
goog.style.setPosition(goog.dom.$('id'), left, top)
// or
goog.style.setPosition(goog.dom.$('id'), new goog.math.Coordinate(x, y))
// gets the offsetLeft and offsetTop properties of an element
// return goog.math.Coordinate
goog.style.getPosition(goog.dom.$('id'))
Element bounds:
// return goog.math.Rect
goog.style.getBounds(goog.dom.$('id'))
Opacity manipulation:
// sets the opacity
goog.style.setOpacity(goog.dom.$('id'), 0.5)
// gets the opacity
goog.style.getOpacity(goog.dom.$('id'))
Hide/Show element:
// hide
goog.style.setStyle(goog.dom.$('id'), "display", "none");
// or
goog.style.showElement(goog.dom.$('id'), false);
// show
goog.style.setStyle(goog.dom.$('id'), "display", "");
// or
goog.style.showElement(goog.dom.$('id'), true);
Document ready listener
The short story is that we don't want to wait for DOMContentReady (or worse the load event) since it leads
to bad user experience. The UI is not responsive until all the DOM has been loaded from the network.
So the preferred way is to use inline scripts as soon as possible.
Require
goog.require('goog.events');
goog.require('goog.events.EventType');
Examples
Adds an event listener for a mouse click event
(more events see in eventtype.js):
goog.events.listen(
goog.dom.$('id'),
'click',
function(event){ /*...*/ }
);
// or
goog.events.listen(
goog.dom.$('id'),
goog.events.EventType.CLICK,
function(event){ /*...*/ }
);
// or
goog.events.listen(
goog.dom.$('id'),
[goog.events.EventType.CLICK, goog.events.EventType.MOUSEOVER], // array of events
function(event){ /*...*/ }
);
Adds an event listener for a mouse click event and remove it after event fired:
goog.events.listenOnce(goog.dom.$('id'), 'click',
function(event){ /*...*/ }
);
Removes an event listener:
// Create an event listener
goog.events.listen(goog.dom.$('id'), 'click', myFunction, true);
// Removes
goog.events.unlisten(goog.dom.$('id'), 'click', myFunction, true);
Removes an event listener by key:
// Create an event listener
var key = goog.events.listen(goog.dom.$('id'), 'click', myFunction);
// Removes
goog.events.unlistenByKey(key);
Removes all listeners from DOM node:
goog.events.removeAll(goog.dom.$('id'));
// or all
goog.events.removeAll();
// callback function
function (event) {
// prevent default action
event.preventDefault();
// stop bubbling
event.stopPropagation();
}
Require
// base for Animation
goog.require('goog.fx');
goog.require('goog.fx.dom');
// queues
goog.require('goog.fx.AnimationQueue');
goog.require('goog.fx.AnimationSerialQueue');
goog.require('goog.fx.AnimationParallelQueue');
// easing
goog.require('goog.fx.easing');
Animation Events
- goog.fx.Animation.EventType.PLAY — when played for the first time OR when it is resumed
- goog.fx.Animation.EventType.BEGIN — only when the animation starts from the beginning
- goog.fx.Animation.EventType.RESUME — only when animation is restarted after a pause
- goog.fx.Animation.EventType.END — when animation comes to the end of its duration OR stop is called
- goog.fx.Animation.EventType.STOP — only when stop is called
- goog.fx.Animation.EventType.FINISH — only when animation comes to its end naturally
- goog.fx.Animation.EventType.ANIMATE — each frame of the animation
- goog.fx.Animation.EventType.DESTROY — when the animation is destroyed
// example of usage
var anim = new goog.fx.dom.FadeIn(goog.dom.$('id'), 1200);
goog.events.listen(anim, goog.fx.Animation.EventType.END,
function(event) {
/* ... */
});
anim.play();
Animation Easing
- goog.fx.easing.easeIn — start slow and speed up
- goog.fx.easing.easeOut — start fastest and slows to a stop
- goog.fx.easing.inAndOut — start slow, speed up, then slow down
Examples
Creates an animation object that fades the opacity of an element
// between two limits
new goog.fx.dom.Fade(goog.dom.$('id'),
1, // start
0.5, // end
1200, // time in ms
goog.fx.easing.easeIn // easing function);
// from completely transparent to fully opacity
new goog.fx.dom.FadeIn(goog.dom.$('id'), 1200);
// from full opacity to completely transparent
new goog.fx.dom.FadeOut(goog.dom.$('id'), 1200);
// from full opacity to completely transparent and then sets the display to 'none'
new goog.fx.dom.FadeOutAndHide(goog.dom.$('id'), 1200);
// sets an element's display to be visible and then fades an element in from completely transparent to fully opacity
new goog.fx.dom.FadeInAndShow(goog.dom.$('id'), 1200);
Slide an element
// from A to B
new goog.fx.dom.SlideFrom(goog.dom.$('id'),
[100, 100], // start X and Y
[400, 400], // end X and Y
2000)
// from current position to B
new goog.fx.dom.SlideFrom(goog.dom.$('id'),
[400, 400], // end X and Y
2000)
Resize an element
// between two widths and heights
new goog.fx.dom.Resize(goog.dom.$('id'),
[100, 100], // start width and height
[200, 200], // end width and height
2000)
// width: element, from, to, time
new goog.fx.dom.ResizeWidth(goog.dom.$('id'), 100, 200, 2000)
// height: element, from, to, time
new goog.fx.dom.ResizeHeight(goog.dom.$('id'), 100, 200, 2000)
Scroll an element from A to B:
new goog.fx.dom.Scroll(goog.dom.$('id'),
[0, 0], // start X and Y
[400, 400], // end X and Y
2000)
Transformation of an elements colors:
// text color
new goog.fx.dom.ColorTransform(goog.dom.$('id'),
[0, 0, 0], // start R,G,B
[255,255,255], // end R,G,B
2000)
// background color
new goog.fx.dom.BgColorTransform(goog.dom.$('id'),
[0, 0, 0], // start R,G,B
[255,255,255], // end R,G,B
2000)
// highlight background color
// calls statically
goog.fx.dom.bgColorFadeIn(goog.dom.$('id'),
[255, 255, 0], // start R,G,B
2000)
Require
goog.require('goog.ui.AnimatedZippy');
goog.require('goog.ui.Zippy');
goog.require('goog.ui.ZippyEvent');
Examples
Basic usage:
new goog.ui.AnimatedZippy(
'clickMe', // header element - DOM element or Id
'slideMe', // content element - DOM element or Id
true // initial expanded/visibility state (=false));
Listen toggle event:
var zippy = new goog.ui.AnimatedZippy('clickMe', 'slideMe', true));
goog.events.listen(zippy, goog.ui.Zippy.Events.TOGGLE,
function(event) {
/* ... */
});
Require
goog.require('goog.net.cookies');
Examples
// check cookies
goog.net.cookies.isEnabled();
// set cookies
goog.net.cookies.set('name', 'value', 60*60*24, '/path/', 'domain.com')
// get cookies
goog.net.cookies.get('name', 'default_value')
// remove cookies
goog.net.cookies.remove('name', '/path/', 'domain.com')
Require
goog.require('goog.net.XmlHttp');
// or
goog.require('goog.net.XhrIo');
Events
- goog.net.EventType.COMPLETE — request completes, either successfully or not.
- goog.net.EventType.SUCCESS — after COMPLETE if the request is successful
- goog.net.EventType.ERROR — after COMPLETE if the request is unsuccessful
- goog.net.EventType.ABORT — after COMPLETE if the abort() method is invoked
- goog.net.EventType.TIMEOUT — request does not complete before the timeout limit is reached
- goog.net.EventType.READY — when a goog.net.XhrIo is ready to be used to make a new request
- goog.net.EventType.READY_STATE_CHANGE — dispatched every time the onreadystatechange handler of the goog.net.XhrIo‘s underlying
XHR is called (need for Comet realization)
Examples
// XMLHTTP Request
// use for synchronous requests only!
var xhr = goog.net.XmlHttp();
xhr.open('GET', url, true /* is Asynchronous */);
xhr.onreadystatechange = function() {
if (xhr.readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
// Data response
xhr.responseText;
}
};
xhr.send(null);
// simple static method
goog.net.XhrIo.send('path/to/server',
function(event){
// if HTML response
event.target.getResponseHtml();
// if XML response
event.target.getResponseXml();
// if JSON response
event.target.getResponseJson();
// if text response
event.target.getResponseText();
},
'POST', // Send method, default is GET
'give=data&return=lost' // Post data
);
// Post data from object
// result: param1=value1¶m2=value2
var dataString = goog.uri.utils.buildQueryDataFromMap({
'param1':'value1',
'param2':'value2'
});
// result: param1=value1.1¶m1=value1.2¶m2=value2
var dataString = goog.uri.utils.buildQueryDataFromMap({
'param1':['value1.1','value1.2'],
'param2':'value2'
});
// normal usage
var xhr = new goog.net.XhrIo;
goog.events.listenOnce(xhr, goog.net.EventType.COMPLETE, function(event) {
var xhr = /** @type {goog.net.XhrIo} */ (event.target);
xhr.dispose(); // Dispose of the XHR if it is not going to be reused.
});
xhr.send('path/to/server', 'POST', dataString);
Bookmarks