Reputation: 17
So I'm attempting to modify a purely HTML/CSS version of the game KuKu Kube, adding a timer, more levels, and a standardized side, but I'll probably be able to figure those out.
So, I have this snippet of code:
var element = document.getElementsByClassName("cube");
element.addEventListener("transitionend", showMessage(), false);
element.addEventListener('webkitTransitionEnd', showMessage(), false);
element.addEventListener('oTransitionEnd', showMessage(), false);
element.addEventListener('transitionend', showMessage(), false);
element.addEventListener('msTransitionEnd', showMessage(), false);
I've spent at least an hour pouring over the code that was there before, and being a novice, my analysis is that the cubes are checkboxes, and they transition.
By the way, JSFiddle here, but I feel the reason it's not working is in those 5 lines.
So, why doesn't the transitionend trigger showMessage()?
Thanks in advance.
Upvotes: 0
Views: 145
Reputation: 3967
You are basically calling all elements with cube - so it's an array - you have to iterate over it to add listeners to all of them. Fiddle Here
var elements = document.getElementsByClassName("cube");
for(var i=0; i<elements.length; i++){
element[i].addEventListener("transitionend", showMessage, false);
element[i].addEventListener('webkitTransitionEnd', showMessage, false);
element[i].addEventListener('oTransitionEnd', showMessage, false);
element[i].addEventListener('transitionend', showMessage, false);
element[i].addEventListener('msTransitionEnd', showMessage, false);
}
Upvotes: 0
Reputation: 32511
Because you're immediately calling showMessage
, not setting it up as an event listener.
For example, if you did this:
var value = showMessage();
console.log(value);
You'd probably see undefined
in your console. Instead, you want to pass the function itself as the argument, not it's return value.
element.addEventListener('transitionend', showMessage, false);
// Notice the lack of () --^
Also, if you open up your console, you'll see that you're getting a
Uncaught TypeError: element.addEventListener is not a function
error. That's because document.getElementsByClassName
returns a collection of nodes, not an individual one. Instead, you should loop through that collection and attach the event to each individual node.
var elements = document.getElementsByClassName('cube');
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
element.addEventListener('transitionend', showMessage, false);
// ...
}
Upvotes: 1