Digital Brent
Digital Brent

Reputation: 1285

Why can't I call this jQuery function?

I need some help understanding some jQuery basics. I have a really simple function here but I can't call it.

<script type="text/javascript">

        jQuery(function ($) {
            callFunc();
        }
                function callFunc(){
                    alert("Function Called!");
                }
        );

 </script>

If I don't put the alert in it's own function it triggers the alert. When I wrap it in a function and give it a name and try to call it, it doesn't work. Please help, I've been looking all over for some straightforward ways of just creating and calling jQuery functions. I've tried passing in the $ as a parameter but no matter what I try, I can't seem to just create a simple function and call it. What am I doing wrong and how do I call my function?

Upvotes: 0

Views: 1273

Answers (2)

Vincent815
Vincent815

Reputation: 139

You have syntax error

Correct syntax:

     jQuery(function ($) {
           callFunc();

           function callFunc(){
                alert("Function Called!");
           }
     });

or:

 jQuery(function ($) {
      callFunc();
 });

 function callFunc(){
      alert("Function Called!");
 }

Just a reminder. jQuery(function ($) {}); is a short hand for jQuery(document).ready(function($){});

Upvotes: 0

Sam Battat
Sam Battat

Reputation: 5745

because of syntax error:

Your code:

jQuery(function ($) {
            callFunc();
        } //missing a closing ) for the JQuery(
                function callFunc(){
                    alert("Function Called!");
                }
        ); //extra ) 

Correct code:

 jQuery(function ($) {
     callFunc();
 });

 function callFunc() {
     alert("Function Called!");
 }

DEMO: http://jsfiddle.net/tnhswf11/

If you want to have the function inside the jQuery:

jQuery(function ($) {
     function callFunc() {
         alert("Function Called!");
     }
     callFunc();
 });

DEMO: http://jsfiddle.net/tnhswf11/1/

Upvotes: 4

Related Questions