Reputation: 73275
I have a menu as follows:
<button id="button" onclick="DropDown(event)">Drop down the menu</button>
<div id="menu">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
The JavaScript for the menu is:
// To close the menu when clicked outside
$(document).click(function() { $('#menu').hide(); });
// When clicking on the items
$('#menu li').click(function () {
$(document).append('<code>Clicked item!</code>');
});
function DropDown(event) {
// Position of the menu
var position = $('#button').offset();
// Position the menu and slide it down
$('#menu').css('top',
(position.top + $('#button').height() + 4) + 'px')
.css('left',
position.left + 'px')
.slideToggle();
event.stopPropagation();
}
Most of the code works as expected: clicking the button drops down the menu and clicking anywhere makes the menu disappear. However, the event handler assigned to the <li>
items is not getting invoked at all, despite the fact that the onclick
handler for the document
is being invoked.
jsFiddle: http://jsfiddle.net/W5SqD/4/
Upvotes: 0
Views: 280
Reputation: 10572
Try attaching the event either in a $(document).ready()
block or via using the live handler. This will ensure that the event is being attached when the element exists. The below worked for me.
// When clicking on the items
$('#menu li').live("click",function () {
alert("Hello!");
$(document).append('<code>Clicked item!</code>');
});
Upvotes: 3