Event binding to dynamic/runtime html elements

There are lot of situation when you need to deal with runtime html elements. In this guide we will walkthrough for creating elements, registering events to elements, detaching events from elements and destroying elements from the html page.

Creating elements if you are using JavaScript( not jQuery library)

In an HTML document, the document object provides a createElement() method that creates the specified HTML element. The document object in any HTML document is the root node and the parent of all other nodes. After loading the html page into a browser, you can access document object.

For the example:
var elemObj = document.createElement(‘put the tagName’);

elemObj is the created Element object. You need to specify the type of element to be created in place of ‘put the tagName’.

The following is the simple HTML document that contains single div element.

<!DOCTYPE html>
  <title>Event handling</title>
  <div id="div1"></div>

Add ‘click’ event to div1

document.body.onload = addDiv;
function addDiv()
	var div1 = document.getElementById("div1");
	var elemDiv = document.createElement('div');
	elemDiv.innerHTML = "Create Button";
	elemDiv.addEventListener("click", createButton);
function createButton()
    var btn = document.createElement("button");
    var text = document.createTextNode("Save");
    btn.appendChild(text );

The ‘createButton’ is a event listner which is the reference of the handler. We can say that event listener refers to a function or object registered via addEventListener() method or by using the following ways:

by HTML attribute, for example:
<button onclick=”createButton(event);”>,

or by setting the corresponding property from JavaScript, for example:
document.getElementById(“btn”).onclick = function(event) { … }.

Using the anonymous function as listener

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. You can use these as:

elemDiv.addEventListener("click", fucntion(){
	var btn = document.createElement("button");
	var text = document.createTextNode("Save");
	btn.appendChild(text );

In the first way, we are using a named identifier for the event listener function so that we can use this later. We can call element.removeEventListener to remove the event but in second way where we are using anonymous function. it is not possible to call element.removeEventListener(that can be case of memory leak :)).