Question

So here is a dumbed down version of what I'm doing. I want to change the onclick for a span to call a function with a variable as its argument. I want it to use the variable as it exists when I create the new onclick not as the variable is at the time of the click.

<html>
<head>
<script>
function share(it) {
  alert("We wanted 1, we got "+ it);
}
</script>
</head>
<body>
<span id="key">Click me</span>

<script>
var x = 1;
document.getElementById('key').onclick = function() {share(x)}
x++;
</script>

</body>
</htmL>
Was it helpful?

Solution

Don't use a function() directly, use a function that creates the onclick function:

<html>
<head>
<script>
function share(it) {
  alert("We wanted 1, we got "+ it);
}

function makeFunction(x) {
return function() {share(x);}
}

</script>
</head>
<body>
<span id="key">Click me</span>

<script>
var x = 1;
document.getElementById('key').onclick = makeFunction(x)
x++;
</script>

</body>
</html>

OTHER TIPS

I think you need this:

<html>
<head>
<script>
function share(it) {
  alert("We wanted 1, we got "+ it);
}
</script>
</head>
<body>
<span id="key">Click me</span>

<script>
function assign(y) {
   return function() { share(y); };
}
var x = 1;
document.getElementById('key').onclick = assign(x);
x++;
</script>

</body>
</html>

make a copy of x and pass that to the function

<html>
<head>
<script>
function share(it) {
  alert("We wanted 1, we got "+ it);
}
</script>
</head>
<body>
<span id="key">Click me</span>

<script>
var x = 1;
var copyOfx = x + 0;
document.getElementById('key').onclick = function() {share(copyOfx)}
x++;
</script>

</body>

All you need to do is just declare the variable in the head. The variable is user-defined and hard coded, so it can load in the head and then just refer to it in the function when the click happens. You don't need to pass a parameter

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top