Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and use a function in jQuery

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?

like image 896
saltandpepper Avatar asked Dec 05 '22 00:12

saltandpepper


2 Answers

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)

like image 154
user113716 Avatar answered Dec 15 '22 06:12

user113716


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.

like image 41
Nick Craver Avatar answered Dec 15 '22 06:12

Nick Craver