Reputation: 93
Good morning,
jsbin attached: http://jsbin.com/kasofufuni/edit?html,css,js,console,output
I'm trying to make a simple show/hide function. I've pared it down to what you can see in the code above, but some sort of syntax error is causing it to not run or give an error. I've been mashing at it for a couple hours. Any ideas?
I got it to work once in a console, but I have not been able to reproduce.
$(document).ready(function(){
$('nav#global').prepend('<span id="menu-icon">Menu</span> <span id="search-icon">Search</span>');
});
$('#menu-icon').on('click',function(){
$('nav#global').prepend('You clicked it');
});
Upvotes: 0
Views: 48
Reputation: 63524
If you don't want to include the code in your document.ready
function, you can use some event delegation:
$(document).on('click', '#menu-icon', function(){
$('nav#global').prepend('You clicked it');
});
Upvotes: 0
Reputation: 171679
Your click event code is outside of document.ready so it runs before element exists
Change to:
$(document).ready(function(){
$('nav#global').prepend('<span id="menu-icon">Menu</span> <span id="search-icon">Search</span>');
$('#menu-icon').on('click',function(){
$('nav#global').prepend('You clicked it');
});
});
Code will run fine in console because element exists then
Upvotes: 1