0

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'); 
});
1
  • 1
    Please add code to this page and not external sites Commented Aug 14, 2015 at 15:04

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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'); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.