addEventListener does not work with parameter passing

2

I have two inputs that both have an id, and I have a button with an oncick event bound (directly in HTML) that receives the value of both input fields as input, now I want to separate javascript into a separate file, but I can not make the javascript function link, below everything in the HTML file:

<input type="file" id="imgPC">
<input type="text" id="imgWEB">
<input type="button" onclick="exibeImagem(imgPC.value, imgWEB.value)" id="btnEnviaImg" value="Enviar"/>
<script type="text/javascript">
     function exibeImagem(imgPCValue, imgWEBValue){
          alert(imgPCValue);
          alert(imgWEBValue);
     }
</script>

As I did with the separate file (I removed the onclick from the input and put the method inside the separate file) so it does not work:

window.onload = function(){
     var btnEnviaImg = document.getElementById("btnEnviaImg");
     btnEnviaImg.addEventListener("click",exibeImagem(imgPC.value, imgWEB.value),false);
}
    
asked by anonymous 10.04.2015 / 16:38

2 answers

4

When you use nomeFuncao(arg_A, arg_B) you are running the function. That is what addEventListener will use as argument is what this function returns ... that's not what you want to use.

If the IDs are fixed you should do so:

btnEnviaImg.addEventListener("click", function(event){
    var imgPCValue = document.getElementById('imgPC').value;
    var imgWEBValue = document.getElementById('imgWEB').value;
    alert(imgPCValue);
    alert(imgWEBValue);
},false);

You can also define the function separately and pass as argument after:

function handler(event){
    var imgPCValue = document.getElementById('imgPC').value;
    var imgWEBValue = document.getElementById('imgWEB').value;
    alert(imgPCValue);
    alert(imgWEBValue);
}
btnEnviaImg.addEventListener("click", handler,false);

If these IDs are not fixed or want to have a relationship in the DOM between the clicked element you can do so, taking into account that this within that function handler is the clicked element.

function handler(event){
    var imgPC = this.previousSibling;
    var imgWEB = imgPC.previousSibling;
    var imgPCValue = imgPC.value;
    var imgWEBValue = imgWEB.value;
    alert(imgPCValue);
    alert(imgWEBValue);
}
btnEnviaImg.addEventListener("click", handler,false);
    
10.04.2015 / 16:50
4

When you pass a callback function as a parameter it is impossible to pass parameters directly, because when you add the parentheses, js executes the function, ie you are passing the result of the function as a parameter , not the function itself.

What you can do is create an anonymous function to call the function with the desired parameters:

btnEnviaImg.addEventListener("click", function() {
    exibeImagem(imgPC.value, imgWEB.value);
}, false);
    
10.04.2015 / 16:46