Tr3y
Tr3y

Reputation: 191

jQuery - Function runs without being told to, please advise

I'm writing a psychology experiment in jQuery. I want to write a function that will begin the exercise when the user presses p or q. I have that working:

$(function trial() {
$("body").keydown(function(e) {
    if (e.which == 81 || e.which == 80)
        {
        $(".message").text("exercise begun (timestamp)");
        var refreshId = setTimeout(timeout, 2000);
        }
});
});

But I'm confused about one thing: this function, trial(), runs automatically. I would like to have to call it, for it to run. For instance, this function

function timeout(x) {
var x = trialNum
$(".message").prepend("Timeout (Trial " + x + ")<br>");
}

which gets called by trial() behaves itself well, it does not run unless called. I assume this has something to do with the $ symbol, and "scope"? All help appreciated.

Oh! Additionally, one more question. I was trying to make a recursive jQuery function and had a lot of trouble with it. What's the best way to make a function call itself?

Upvotes: 3

Views: 3572

Answers (7)

Kevin Pei
Kevin Pei

Reputation: 5872

Try doing this: $(function trial() will make it run automatically.

I don't know why so, but jQuery just does it like that. You are fine to just keep it as function trial(). As for repeating the function, just put the function name in the function and call the function externally like this:

function trial() {
    $("body").keydown(function(e) {
        if (e.which == 81 || e.which == 80)
        {
            $(".message").text("exercise begun (timestamp)");
            var refreshId = setTimeout(timeout, 2000);
        }
    });
    trial();
}
trial();

However, I do not recommend this, because it will cause an infinite loop that can crash the tab.

Upvotes: -1

FishBasketGordo
FishBasketGordo

Reputation: 23142

By surrounding function trial() { ... } with $( and );, you're calling it when the document is ready. It's shorthand for $(document).ready(function trial() { ... });[API Ref]

If you don't want to do that, remove the surrounding $( and );.

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227240

trial() runs automatically because it is inside the $() function. $(function(){}) is the same as $(document).ready(function(){}).

$(function trial(){}); creates a function called trial in its scope, and then runs it when the DOM is ready.

Just declare the function normally:

function trial(){
  // Code
}

Or, if you want it declared when the DOM is ready, you can declare it inside $() (NOTE: trial will only exist inside the $() function):

$(function(){
    function trial(){
      // Code
    }
    trial();
});
trial(); // won't work, it's out of scope

Upvotes: 0

Frenchi In LA
Frenchi In LA

Reputation: 3169

Try the following:

$(function(){
trial = function(){
// Your code here
};
});

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074266

It's because you're passing a reference to it into $() (aka jQuery()), which is a shortcut for the ready function and runs when the DOM is loaded.


Off-topic: BTW, by doing that, you're using the function as a right-hand value (like something on the right-hand side of an = sign). That makes it a function expression. Since you've named the function (which is a good thing to do), it's a named function expression. Those have historically not worked well in various JavaScript implementations. Most current browsers are (now) okay, except IE prior to IE9 which will create two completely separate functions, more here: Double take

Upvotes: 10

js-coder
js-coder

Reputation: 8346

$() is a short cut for the DOM ready event. It just executes the function passed to it. To solve it, use $(document).ready itself:

$(document).ready(function(){
   function trial() {
        $("body").keydown(function(e) {
        if (e.which == 81 || e.which == 80){
             $(".message").text("exercise begun (timestamp)");
             var refreshId = setTimeout(timeout, 2000);
        }
   }
});

Upvotes: 0

zzzzBov
zzzzBov

Reputation: 179046

To answer your first question, $(function(){...code...}) is the jQuery shortcut for $(document).ready(function(){...code...}); which runs as soon as the DOM has reached the ready state.

About your second question (it does belong in a separate question on SO, but i'll answer it anyway):

Functions in jQuery are no different than functions in JavaScript. Named functions can call themselves recursively using thier own name:

function foo(bar, baz)
{
  ...do some stuff...
  if (--bar)
  {
    foo(bar, baz);
  }
}

You'll have to be more specific as to what you want to achieve with the recursive function, and if you're going to do that, please open a separate question on StackOverflow.

Upvotes: 2

Related Questions