Horai Nuri
Horai Nuri

Reputation: 5578

How to handle addEventListener and attachEvent conflict?

I'm creating a drop or click file upload. I'm having an issue handling the difference between the click & the drop since one use addEventListener and the other one use normal javascript method.

HTML

<input id="imageLoader" type="file" name="imageLoader">

Javascript :

  var imageLoader = document.getElementById('imageLoader');

  /* console shows : ..change { 
    target: <input#imageLoader>, 
    isTrusted: true, 
    currentTarget: <input#imageLoader>, 
    eventPhas... } 
  */
  imageLoader.addEventListener('change', handleImage, false);

  /* console shows : undefined */
  imageLoader.onchange = function(){
    handleImage();
  };

  function handleImage(e){
    console.log(e);
  }

How can I show the same values as the addeventlistener method using the other way ?

Upvotes: 1

Views: 164

Answers (1)

cнŝdk
cнŝdk

Reputation: 32145

In fact addEventListener accepts a callback function in which you can call any code you want.

So instead of just passing your handleImage function directly as a callback you can create a callback function that calls your handleImage function.

imageLoader.addEventListener('change', function(e){
     //do whatever you want here
     handleImage()
}, false);

For attaching the event with onchange you can use the same approach :

imageLoader.onchange = function(event) { 
    //do whatever you want here
    handleImage(event); 
};

Upvotes: 2

Related Questions