1

When I make a function which should be run after onclick event and the function is without argument it works fine - the function is launched after clicking the button. But when I want to pass some argument, the function is run right after loading the page without clicking the button. See both codes:

<script>
var hash_btn = document.getElementById("btn_hash");
var hash_txt = document.getElementById("txt_hash");

var test_f = function(txt)
{
  alert('hello');
}

// this alerts 'hello' after clicking the button
hash_btn.onclick = test_f; 

// this alerts 'hello' immediately without clicking the button
hash_btn.onclick = test_f('whatever');

</script>
<html>
<input type="text" id="txt_hash" />
<input type="button" id="btn_hash" value = "Hash"/>
</html>
Lukáš Ježek
  • 75
  • 3
  • 11
  • 4
    That's because `functionName(something)` means "call this function right now". – Pointy Jan 26 '18 at 13:47
  • common question should be marked as dupe, but you would use .bind() or closure. – epascarello Jan 26 '18 at 13:50
  • Even if the linked duplicate uses `addEventListener` and not `onclick`, the problem and solution are still the same. `hash_btn.onclick = function() { test_f('whatever'); };` – t.niese Jan 26 '18 at 13:59

2 Answers2

0

When you run this line, you are saying basically, that the function should ve invoked, not assigned:

hash_btn.onclick = test_f('whatever');

One possible solution is to actually adding it to the HTML tag. Use this just to confirm your situation and current issue. As commented below, it has some disavantages that you would want to avoid as you move forward with coding:

<input type="button" id="btn_hash" value = "Hash" onclick="test_f('whatever')"/>
sebastianf182
  • 9,844
  • 3
  • 34
  • 66
  • 1
    You should never use inline event handlers. It makes to code harder to maintain, prevents the usage of code minification tools, linter won't detect that `test_f` is used, and you need to make `test_f` available in the global scope. – t.niese Jan 26 '18 at 14:00
  • True, but I also said it is one possible solution. If he does not have the knowledge yet to detect this issue by himself, then I believe those are advanced topics. I'll modify my answer – sebastianf182 Jan 26 '18 at 15:12
0

By writing hash_btn.onclick = test_f(arg); you execute the function. It's like writing

var result = calculate(5,10);, which will return the calculated result.

If you want to assign your function to the onclick-handler you need to give it a reference to the desired function.

element.onclick = functionRef;

where functionRef is a function - often a name of a function declared elsewhere or a function expression.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick

In Code:

hash_btn.onclick = () => { test_f('yourArgument'); };

In HTML (Not recommended):

<input type="button" onclick="test_f('yourArgument')"/>
Community
  • 1
  • 1
S. Stumm
  • 290
  • 1
  • 9