Demonstrates delegated event handling.
<p>The .on() is attached to the container div for the red and green input elements. The blue input is added to the div with the red and green inputs. The purple input is added to the body. Type text in the inputs before and after clicking the buttons</p>
<div id="inputs">
<input id="red" type="text" style="background-color: #FFDDDD;" />
<input id="green" type="text" style="background-color: #DDFFDD;" />
</div>
<button id="addBlueInput">add blue input with others</button><br/>
<button id="addPurpleInput">add purple input to body</button><br/>
JavaScript
$('#inputs').on('keydown', 'input', function(e){
console.log(e);
});
$('#addBlueInput').on('click', addBlueInput);
$('#addPurpleInput').on('click', addPurpleInput);
// adds to same container div
function addBlueInput(){
var i = $('<input id="blue" type="text" style="background-color: #DDDDFF;">');
$('#inputs').append(i);
}
// adds to *body*
function addPurpleInput(){
var i = $('<input id="purple" type="text" style="background-color: #F0DDFF;">');
$('body').append(i);
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.