Reputation: 177
I am trying to understand the following JavaScript code I have found (and actually use) in Masonry:
var docElem = document.documentElement;
var transitionProp = typeof docElem.style.transition == 'string' ?
'transition' : 'WebkitTransition';
var transitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
transition: 'transitionend'
}[ transitionProp ];
Does the expression {}[] mean, that the transitionProp variable is added to transitionEndEvent object? And is the Expression typeof docElem.style.transition someway of finding out if css transition is supported?
Thanks for your help!
Upvotes: 3
Views: 130
Reputation: 309
It's returning that particular element of the object.
For example:
var obj = { key: 'value' };
var val = obj['key']);
Could be shortened to:
var val = { key: 'value' }['key'];
(Obviously in this case it's pointless, but it illustrates what is happening.)
Upvotes: 4
Reputation: 2046
here transitionEndEvent
will contain:
'webkitTransitionEnd'
if transitionProp == 'WebkitTransition'
or
'transitionend'
if transitionProp == 'transition'
Upvotes: 0
Reputation: 655
To add some property to JSON we use
object["property"] = value;
So the above lines in your code is written to access the property name transitionProp from the object.
So the variable transitionEndEvent will hold the value of transitionProp property.
var transitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
transition: 'transitionend'
}[ transitionProp ];
Upvotes: 0
Reputation: 15846
The initial two lines,
var docElem = document.documentElement;
var transitionProp = typeof docElem.style.transition == 'string' ?
'transition' : 'WebkitTransition';
will assign value transition
or WebkitTransition
to transitionProp
.
Then you create an object and by using [transitionProp]
it will be more like the value of transitionProp
inside ['transition'/'WebkitTransition']
.
var transitionEndEventObj = {
WebkitTransition: 'webkitTransitionEnd',
transition: 'transitionend'
};
var transitionEndEvent = transitionEndEventObj[ transitionProp ];
in other terms it will look either like this
var transitionEndEvent = transitionEndEventObj[ 'transition'];
or
var transitionEndEvent = transitionEndEventObj['WebkitTransition'];
Upvotes: 0