The first half of this code works perfectly. However the second. Where an items is removed if you click it does not fire.
$(document).ready(function()
{
$('#contact').click(function()
{
$('#contact_box').remove();
$('.menu_item_content').prepend('<div class="menu_box" id="contact_box">Contact INFO goes in this box.</div>');
});
$('#about').click(function()
{
$('#about_box').remove();
$('.menu_item_content').prepend('<div class="menu_box" id="about_box">About info goes in this box.</div>');
});
$('#twitter').click(function()
{
$('#twitter_box').remove();
$('.menu_item_content').prepend('<div class="menu_box" id="twitter_box">Twitter</div>');
});
//
//remove single items
//
//nothing below this fires for some reason?
$('#contact_box').click(function()
{
$('#contact_box').remove();
});
$('#about_box').click(function()
{
$('#about_box').remove();
});
$('#twitter_box').click(function()
{
$('#twitter_box').remove();
});
});
<style>
.menu_item
{
display:inline;
font-family:Tahoma;
font-size:20px;
}
.menu_spacer
{
display:inline;
font-family:Tahoma;
font-size:45px;
}
</style>
<div class="menu">
<div class="menu_items">
<div class="menu_item" id="contact">CONTACT</div>
<div class="menu_spacer">/</div>
<div class="menu_item" id="about">ABOUT</div>
<div class="menu_spacer">/</div>
<div class="menu_item" id="twitter">TWITTER</div>
</div>
<div class="menu_item_content">
</div>
</div>
Since your ‘adding’ those elements in your first part, you need to use
.live()or.delegate()to bind those below events.example:
If you create items on the fly and you miss to directly bind events to them, they don’t know about your event handler. That makes total sense, since the execution of that code (which binds the event handler) happens before those elements are beeing created.
.live()and.delegate()kind of “workaround” this behavior. Instead of binding an event handler to the element itself, they are binding an event handler to a parent node. Javascript events will “bubble up” each node (if that isn’t prevented), so.live()will “watch” at thedocument.bodyforclick eventsafter that binding. If it catches an event, it checks thetarget idand fire your code if it matches.Now you could say, -boy oh boy, that is like a lot of overhead- and you would be correct.
.live()will watch at the top of your document tree, which is the body. That means, any event bound via.live()has to bubble up throw any node that is inbetween.So the clever folks from
jQuerysaid, wait a second, if you know the root node for any new element you are going to create on the fly, it should be enough to watch for bubbling events right there and.delegate()was born. You can tell.delegate()the parent node to observe, no more overhead!Reference: .live(), .delegate()