-3

How to attach javascript function while dynamic creating the element.

Thanks

ManojSoni
  • 13
  • 4
  • 1
    A little search would help: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – artuc Dec 04 '14 at 13:52

2 Answers2

0

welcome to stackoverflow. you should get more precise on your questions, if you want good answers. e.g. code snippets, what you've tried so far and so on...

since you tagged jquery to your question, i'll answer with the jquery specific solution.

dynamic created elements's can't directly be used to bind anything to them, since they are not initially known to the dom. so you have to bind the function to an existing element and use event delegation.

this works with the .on() function.

$(".existingelement").on("click", ".dynamicelement", function(){
  //do stuff here
})
errand
  • 980
  • 1
  • 7
  • 18
0

 $('#ulTagContent').html("");
                for (var i = 0; i < TagListInfo.length; i++) {

                    var li = document.createElement('li');
                    li.className = ''; // Class name
                    // li.innerHTML = ; // Text inside
                    li.id = "li"+i;
                    $('#ulTagContent').append(li); // Append it
                    //li.onclick = dynamicEvent; // Attach the event!
                    
                    var Anchor = document.createElement('a');
                    Anchor.id = "anchor" + i;
                    Anchor.innerHTML = TagListInfo[i].TagName;

                    var TagName = TagListInfo[i].TagName.trim();

                    Anchor.href = "javascript:;";
                    var GroupId = i + 1 ;
                    Anchor.setAttribute("onclick", "ShowGalleryByTagName('" + TagName + "'," + GroupId + ");")
                   
                    $('#li' + i).append(Anchor);
                }
            }
  <ul style="padding: 0" class="tag-list" id="ulTagContent"></ul>
ManojSoni
  • 13
  • 4