Here is the scripts: http://jsbin.com/itusut/6/edit
Hi, i have function:
function on(t, e, f) {
if ( e.length ) {
var l = e.length,
n = 0;
for ( ; n < l; n++ ) {
e[n].addEventListener(t, f, false)
}
} else {
e.addEventListener(t, f, false);
}
}
if we do var handle = document.getElementsByClassName('some-class');
then handle
is a node list.
if we do var handle = document.getElementById('an-id');
then handle
is a single node.
The problem is, when i choose <form id="login-form">
it returns array not single element.
So, my on
function is fail. The function use elm.length
filter. Everything is ok, except for <form>
. How to fix this? i know elm.length not work properly on single node <form>
element.
Would you help? Thank you very much
Form elements have a length property (to tell the number of fields in the form). The code you're using doesn't accurately detect whether the element is a DOM node, so it assumes that the form is a collection of DOM nodes.
If you need to bind elements, you're probably better off always passing in an array or array-like object, so that the function always iterates over the collection.
This could be as simple as wrapping the parameter in an array:
on('click', [formElement], callback);
on
where only lists are supported:function on(type, elements, callback) {
var length,
i;
length = 0;
if (elements && elements.length) {
length = elements.length;
}
for (i = 0; i < length; i += 1) {
elements[i].addEventListener(type, callback, false);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With