Nick
Nick

Reputation: 33

dynamically making onClick event?

I realise a similar issue has been asked here Javascript - Dynamically assign onclick event in the loop but I think I was a bit confused and couldn't add a comment.

I'm making a series of divs dynamically, in an array "newdiv". I want to create an onClick function which will expand the offsetHeight to the scrollHeight.

I'm trying to do this in my for loop as such:

newdiv[i].onclick = function() {expandThis(message_id) };

Where

message_id = message_array[i][0];

(the id column in the array, at message 'i')

The problem is familiar - all the made onClicks refer to the last message_id. Is there an easy way to make the onClick for newdiv[i] refer to message_array[i][0]?

Upvotes: 0

Views: 267

Answers (3)

RobG
RobG

Reputation: 147363

You need to break the closure with message_id:

newdiv[i].onclick = (function(id) {
                       return function() {expandThis(id) };
                    }(message_id));

There are a million questions like this one, e.g. Do while javascript Problem.

Upvotes: 0

jasonc65
jasonc65

Reputation: 51

You could use an anonymous function to create a closure to contain the value to be referred to.

function(message_id) {
  newdiv[i].onclick = function() {expandThis(message_id) };
}(message_array[i][0]);

JavaScript is a functional programming language without a let statement. So you have to write the equivalent closure, as ugly as it looks.

Upvotes: 1

user400055
user400055

Reputation:

you could create the javascript code dynamically and store in in a var and then use the evalute() function and assign the result to your onclick callback.

Upvotes: 0

Related Questions