0

I have a function to attach a event:

function addEvent(object, type, callback) {
    if (object == null || typeof(object) == 'undefined') return;
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
};

And a tiny button to test:

<a href="#" class="btn btn-primary btn-toggle" id="btn-toggle-action">Toggle</a>

I try to call it but I've seen:

addEvent(document.getElementById('btn-toggle-action'), 'click', function(e) {}); //WORKS

addEvent(document.getElementByClassName('btn-toggle'), 'click', function(e) {}); //DON'T WORK

addEvent($('.btn-toggle'), 'click', function(e) {}): //DON'T WORK

addEvent($('#btn-toggle-action'), 'click', function(e) {}); //DON'T WORK

I'd like to understand why it can't work with all methods.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Lolo
  • 527
  • 2
  • 8
  • 26
  • I don't understand the point of this function.... if you want to bind events to elements then why not just use `document.getElementById('element').addEventListener('click', function(){});` or jQuery's `$('#element').on('click', function(){});` it's like you're trying to reinvent the wheel.. – NewToJS Oct 09 '16 at 04:08
  • `$(anything)` returns a jQuery object, not an element ... `document.getElementByClassName` is not even an existing function ... the only version above that returns an element is `document.getElementById` - your developer tools console would've alerted you to these fundamental errors – Jaromanda X Oct 09 '16 at 04:09
  • NewToJS, the client want his site works on IE8 then I need to use attachEvent too. And yes I could use $('...') but as we use this function to handle some window events (resize, ...) i'd like to use this function to have a "better" code instead of $('..'), addEvent mixed. And the last but not the least I've learnt a lot :) – Lolo Oct 09 '16 at 04:22

2 Answers2

1

Firstly, write error: document.getElementByClassName should be document.getElementsByClassName, because it select mutiple elements.

jquery selector is diffrent from native selector, see document-getelementbyid-vs-jquery

You can use more powerful native selector like:

document.querySelector('#btn-toggle-action')

document.querySelectorAll('.btn-toggle')

Community
  • 1
  • 1
ColorWin
  • 56
  • 1
  • 7
  • or `document.querySelector('.btn-toggle')` to get a single (first) element with such a class, is perfectly valid too – Jaromanda X Oct 09 '16 at 04:10
-1

May be document.getElementByClassName('btn-toggle') returns array of objects. Need:

if(typeof object === 'array'){
  for(obj in object){
    ...
  }
}

PS. The $() returns $-object, but no dom-element.

jerome
  • 1
  • 1
  • `May be document.getElementByClassName('btn-toggle') returns array of objects` - may be it doesn't because there's no such function – Jaromanda X Oct 09 '16 at 04:10