I am trying to implement a simple mobile menu, but using Nice Menus as my base. So to get things the way the snippet's CSS is set up, I'm using JQuery to dynamically add a <button>
element that can be clicked.
Problem is, nothing happens when I click the button. I've checked that my code works fine when the user clicks a <p>
element. And I have also confirmed with code that the element to which I'm attaching the click function exists. (But it wasn't working with a $(document)
scope either.)
Doesn't work:
$('.nice-menu-main-menu').before('<button class="nav-button">Toggle Navigation</button>');
if ( $('.nav-button').length > 0 ) {
console.log("nav-button element exists"); // console shows this message
$('.nav-button').click( function() {
console.log("menu button clicked"); // never see this message
});
}
Doesn't work:
$( document ).delegate('.nav-button', 'click', function() {
console.log("button clicked"); // never see this message
});
Does work:
$( document ).delegate('p', 'click', function() {
console.log("button clicked"); // console shows this, no problem
});
What magic am I missing? I figure the issue must be with the dynamic aspect of the element, but everything I'm finding in the documentation of JQuery and similar code online suggests this should be working.