0

I have a function that creates a new <a> element and I want to add a onclick event to it, which is a function that increases the given value by 1.

In the function, I create these elements:

A number within spantags:

        var spantags = document.createElement("span");
        var anzahl = 1;
        spantags.innerHTML = anzahl;

And the mentioned <a> element:

        var plus = document.createElement("a");
        plus.innerHTML = "+";
        plus.onclick = more(spantags.innerHTML);

This, however, executed the function already in the function that creates this, so the number was increased to 2 on creation.

I read this answer on a similar question: https://stackoverflow.com/a/249084/1972372

This example worked, the alert only came up when the + was clicked on, but it is an inner function there, not a declared one like my "more(element)".

So my question is: Is it possible to set the onclick attribute to a declared function on a newly created element, like in my example, but prevent it from running immediately?

(The other article had a jQuery answer too, but unfortunately I have no knowledge about jQuery and cannot use it)

2 Answers 2

3

Yes, just wrap it in a "proxy" function:

plus.onclick = function() {
    more(spantags.innerHTML);
};
Sign up to request clarification or add additional context in comments.

Comments

1

Sure, but first you have to understand that plus.onclick = more(spantags.innerHTML); will call more with the argument spantags.innerHTML and assign the result that is returned from that function call to plus.onclick.

You could wrap it in a proxy function as suggested previously, or you could take advantage of the bind method to bind the arguments to the function itself:

plus.onclick = more.bind(null, spantags.innerHTML);

Read up on Bind here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

3 Comments

This wouldn't actually have the same result. You'd be binding the current value of spantags.innerHTML ("1" at the time of binding), and will never increment past 2
It actually works with this, so I'll give this an upvote too, but I am confused about what the first parameter is. I read that it is the this argument, but I still don't really get it. I accepted the first answer because it was easier to understand.
It's the "this" context. In the callback itself, using "this" will reference whatever you pass in as the first argument (in this case "null").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.