4

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

What I've got now:

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

but when I call it like this:

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

it doesn't work. What am I doing wrong?

bzlm
  • 9,456
  • 5
  • 62
  • 90
saltandpepper
  • 958
  • 2
  • 10
  • 30

3 Answers3

9

This may be a typo, but you're missing the $ before the jQuery selector, and you need to be sure the DOM is ready before running this code:

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

Doing $(function() { ... }); is a shortcut for jQuery's .ready() method which makes sure the DOM is ready before your code runs. Selecting first_link does no good if it doesn't exist yet. :o)

user113716
  • 310,407
  • 61
  • 442
  • 435
4

Unless it's a typo, you're missing the $ or jQuery at the start:

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

Or a bit shorter, and maintaining context:

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

In any case, you should be seeing an error in your console (provided you're executing this when #first_link is present (e.g. `document.ready)), always check your console to see what's blowing up.

Nick Craver
  • 610,884
  • 134
  • 1,288
  • 1,151
3

EDIT: Your problem is definitely that you forgot the $ or jQuery before you used jQuery.

Also you can just do ("#first_link").click(adjust_menu)

shoebox639
  • 2,262
  • 15
  • 13
  • Not my downvote - but this wouldn't resolve any problem, though it's better in most respects...it wouldn't really solve any error compared to the original code. – Nick Craver Nov 03 '10 at 22:35