Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript vs jQuery Function Difference?

I've been making a program and I want to know the difference between starting two functions like so:

$(function () {
   //content
});

and

function Name () {
    //content
}

Also, why can't I name the first example? I tried changing the first example to the second type, and the function stopped working fully. I've used jQuery with the first example and everything was fine, but with a different example, the function stopped working.

So what's the difference?

like image 333
Bradley Mitchell Avatar asked May 18 '13 19:05

Bradley Mitchell


4 Answers

$(function () {}); this is shortcut for $(document).ready(function(){});

while this:

function Name () {
    //content
}

is standard javascript function.

  • http://api.jquery.com/ready/
  • http://www.w3.org/wiki/JavaScript_functions
like image 145
Mohammad Adil Avatar answered Oct 19 '22 03:10

Mohammad Adil


The first is a function expression that is used for the jQuery ready event, while the second is a function.

Using $(function(){...}); is shorthand for $(document).ready(function(){...});.

The ready event happens when the document has completed loading, so the event handler will run automatically. A regular function doesn't run at all unless you call it.

You can naturally use a regular function instead of the function expression for the event handler:

function readyHandler() {
  ...
}

$(readyHandler); // or $(document).ready(readyHandler);

A function expression can be named, for example:

var x = function y() { ... };

However, the name of the function expression (y in the example) is not global, it's only usable inside the function itself. Also, the exact implementation of this differs between browsers, so you should avoid using it.

like image 26
Guffa Avatar answered Oct 19 '22 01:10

Guffa


The first one is a so-called anonymous function. It gets executed on the document ready event

$(document).ready(...);

and is jQuery convention. Since you cannot call it directly, it has no / needs no name.

The second version is a standard function that you can call by name at any time.

If you change the first one to the second notation, it will no longer run at document ready automaticly. Safe way is to move the "worklaod" into a function with the second notation, and create a line with the first notation that calls the funciton. That way you have the best of both worlds: a separately callable function, and simple auto-execution.

like image 24
Zsolt Szilagyi Avatar answered Oct 19 '22 01:10

Zsolt Szilagyi


The first one:

 $(function () {
 //content
 });

is passing an anonymous function to the jQuery object $, equivalent to $(document).ready(function(){});

the second is just a JavaScript function named Name.

like image 25
mohamed elbou Avatar answered Oct 19 '22 02:10

mohamed elbou