Delegate Events

Testing delegate to automatically apply events to new elements

by Terry King

HTML

Mouse over box to show element name. Events aren't assigned to new boxes manually but handled automatically by the delegate.
<div class="sandbox"><div class="test" name="1"></div></div>
<div id="results"></div>
<button id="new">new box</button>

CSS

.sandbox{
  position:relative;
  width:600px;
  height:300px;
  border:2px solid #000;
}
.test{
    position:absolute;
    display:block;
    width:50px;
    height:50px;
    background-color:#F00;
    border:1px solid #000;
}
#results{
  position:relative;
    height:40px;
}

JavaScript

var boxcount=1;
$(document).delegate('.test','mouseenter',function(e){
    $('#results').text($(this).attr('name'));
    $(this).on('mouseleave',function(){
        $('#results').text("");
    });
});
$('#new').click(function(){
    $('.test').after('<div class="test" style="left:'+Math.random()*550+'px;top:'+Math.random()*250+'px;" name="'+(++boxcount)+'"></div>');
});