0

i am creating 'li' element dynamically through a loop and i m getting problem in assigning event to each element that is generated dynamically.I want to do assign event onclick on each li element that is generated.

Here is the code:

var not = [{
  "event": "It's your friend's Birthday. Wish him luck!!!",
  "view": "unread",
  "status": "read",
  "image": "<img src='cake.jpg' style='height:80px';'width:80px'>"
}]

var ids = ["id1", "id2", "id3", "id4", "id5"];
var lis = new Array(10);
var i = 0;

for (i; i < not.length; i++) {
  lis[i] = document.createElement("li");
  var obj = document.createTextNode(not[i].event);
  lis[i].appendChild(obj);
  document.body.appendChild(lis[i]);
  lis[i].setAttribute('id', ids[i]);
  var x = document.getElementById(ids[i]);
  x.addEventListener("click", func('ids[i]'));
  document.body.appendChild(ids[i]);

}

function func(a) {
  document.getElementById(a).innerHTML = "hello";
}

similarly there are 5 more not objects.

5
  • 1
    What is the problem? What is not? What is not[i].event? Commented Jan 5, 2016 at 10:33
  • x.addEventListener("click", func()) should be x.addEventListener("click", func) Commented Jan 5, 2016 at 10:36
  • What is not? What is not[i].event? Commented Jan 5, 2016 at 11:18
  • not is an object(json). var not = [{ "event" : "It's your friend's Birthday. Wish him luck!!!", "view" : "unread", "status" : "read", "image" : "<img src='cake.jpg' style='height:80px';'width:80px'>" }, Commented Jan 5, 2016 at 11:25
  • Please include the var not in the code block of you post to avoid confusion Commented Jan 5, 2016 at 11:31

2 Answers 2

1

Try replacing

x.addEventListener("click", func());

by

x.addEventListener("click", func);

If you use func() you are calling the function and send the return value of func(), instead of passing the function itself.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thanks for replying actually i wanted to assign events to each of the element generated in a loop itself..is it possible? its not working on every element
0

Try using .bind, to bind value to event listener. When you do

x.addEventListener("click", func('ids[i])');
  1. You are assigning return value of func to event listener.
  2. 'ids[i]' is not a variable. Its a string.

Replace following to:

x.addEventListener("click", func.bind(ids[i]));

Comments

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.