EN
JavaScript - How to bind event on dynamically created elements?
7
points
In JavaScript, it is possible to bind events on dynamically created elements in the following way.
1. Event listener in pure JavaScript (VanillaJS).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
var element = document.createElement('button');
element.addEventListener('click', function(event) {
this.innerText = 'Button clicked!';
});
element.innerText = 'Click me!';
document.body.appendChild(element);
</script>
</body>
</html>
Note: as first argument for
addEventListener
method we can type any event from this list depending on what type of object we work.
Result:
2. element.on[eventname]
property in pure JavaScript (VanillaJS).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<script>
var element = document.createElement('button');
element.onclick = function(event) {
this.innerText = 'Button clicked!';
};
element.innerText = 'Click me!';
document.body.appendChild(element);
</script>
</body>
</html>
Note: in above code we can use as event property different combination of on + event name from this list depending on what type of object we work e.g. onmoveseover, onmouseout, ondblclick, etc.
Result:
3. jQuery
on
method example
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<script>
var element = document.createElement('button');
$(element).on('click', function(event) {
this.innerText = 'Button clicked!';
});
element.innerText = 'Click me!';
document.body.appendChild(element);
</script>
</body>
</html>
Note: as first argument for
jQuery.prototype.on
method we can type any event from this list depending on what type of object we work.
Result: