1

Having an issue calling a jquery function from a javascript function. I am sure I have done it before... just cant understand the issue I am having. Thanks for any help you could provide.

$(document).ready(function(){
    function funB() {
        alert("B is working");
    };
});

funA();
function funA() {
    alert("A is working");
    funB();
};

http://jsfiddle.net/dannyj6/8GXhh/4/

DannyBoy
  • 117
  • 4
  • 13

5 Answers5

5

Your funB is defined in the scope of the function provided to the ready handler, it is not in global scope. Just move it outside.

$(document).ready(function(){
  funA();
});

function funB() {
  alert("B is working");
}

function funA() {
  alert("A is working");
  funB();
}
mvw
  • 5,075
  • 1
  • 28
  • 34
0

The problem has nothing really to do with jQuery vs. JavaScript; jQuery is JavaScript.

The problem is that "funB" is declared inside another function, and you're trying to refer to it from outside the function. That can't be done.

You could declare "funB" outside the "ready" handler, or you could put the other code inside along with it.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

Because funB is "private" since it is not defined in global scope like you are calling it. If you were to move the code inside the same scope block it would magically start working.

epascarello
  • 204,599
  • 20
  • 195
  • 236
0

It has nothing to do with jQuery (which is just a library, written in Javascript; there are no "jQuery functions".

Your funB() function is declared inside another function; it only exists in that scope. There's no funB() available to the outside world.

This would work:

function funA() {
    alert("A is working");
    funB();
};

function funB() {
    alert("B is working");
};

$(document).ready( funB );

funA();
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
0

You either need to put them within the same enclosure:

$(document).ready(function(){
    function funB() {
        alert("B is working");
    };

    function funA() {
        alert("A is working");
        funB();
    }; 
    funA();   
}); 

Example fiddle

Or alternatively, put funB on the window so it's accessible from funA:

$(document).ready(function(){
    window.funB = function() {
        alert("B is working");
    };
});

funA();
function funA() {
    alert("A is working");
    funB();
};

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339