Joaquin Morales Luque
Joaquin Morales Luque

Reputation: 13

Onclick function triggered with page load instead of clicks

I have been searching about this issue with onclick triggers that actually trigger with page/window load, but could find a solution for the following.

I need to the id of the latest clicked button, so I did this:

 var lastButtonId = [];//to get the latest Id
// then the onclick statements:
 document.getElementById('traffBut').onclick = sendButtonId('traffButton');
 document.getElementById('convBut').onclick = sendButtonId('convBut');
 document.getElementById('revBut').onclick = sendButtonId('revBut');
 document.getElementById('tranBut').onclick = sendButtonId('tranBut');
//Below the funstion to get the last Id:
 function sendButtonId (clikedButton)
       {
        lastButtonId.splice (0,1,clikedButton);   
         console.log(lastButtonId);
       }

But the console shows the following on Page Load: Click here to see console logs

I have tried different ways of doing this but can't get mu head around it,

I hope someone can give me a hint :)

Many thanks J.

Upvotes: 1

Views: 649

Answers (1)

WSH
WSH

Reputation: 341

It's because you must pass a function to the onclick attribute, and not a function call. I mean, you must not call the function you want to be called on click, but instead pass a reference to the function.

So, if you want to call sendButtonId, just write:

document.getElementById('traffBut').onclick = sendButtonId;

Though, as you want to add arguments to the function call, you must create a new function that will automatically apply this argument when called. It can be done using .bind, which returns a new function with the given parameters:

document.getElementById('traffBut').onclick = sendButtonId.bind(this, 'traffButton');

Upvotes: 4

Related Questions