How to declare and use a function in jQuery

I am wondering how I should declare a function in a jQuery script.

What I have:

function adjust_menu() { alert("test test"); }; 

but when I call it this way:

 ("#first_link").click(function() { adjust_menu(); }); 

he does not work. What am I doing wrong?

+4
source share
3 answers

It may be a typo, but before the jQuery selector you are missing $ , and you should be sure that the DOM is ready before running this code:

 $(function() { $("#first_link").click(function() { adjust_menu(); }); }); 

Doing $(function() { ... }); is a shortcut to the jQuery .ready() method , which ensures that the DOM is ready before your code runs. Choosing first_link not appropriate if it does not already exist .: O)

+9
source

If this is not a typo, you are missing $ or jQuery at the beginning:

 $("#first_link").click(function() { adjust_menu(); }); 

Or a little shorter and maintaining context:

 $("#first_link").click(adjust_menu); 

In any case, you should see an error on your console (if you execute it when #first_link present (for example, `document.ready)), always check the console to see what happens.

+4
source

EDIT: Your problem is that you forgot $ or jQuery before using jQuery.

You can also just do ("#first_link").click(adjust_menu)

+3
source

All Articles