Demonstrates delegated event handling

Demonstrates delegated event handling

by Spencer Wasden

HTML

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);
}