How to attach javascript function while dynamic creating the element.
Thanks
How to attach javascript function while dynamic creating the element.
Thanks
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
})
$('#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>