Home > Enterprise >  Call a function from another function
Call a function from another function

Time:09-23

I get

Uncaught ReferenceError: ColorSwitcher is not defined

error. what is my mistake? Also I want to make ColorSwitcher function to a callback function

var BackgroundColor = "red";
 jQuery(document).ready(function ColorSwitcher ($) {
            //add red color to some classes via variable
});

jQuery(document).ready(function($) {
    $("ul.colors .color2").click(function () {
        BackgroundColor = "pink"; // change the color
        ColorSwitcher(); //run the function again to change colors of the classes with new color
        return false;
    })
});

CodePudding user response:

It's because your ColorSwitcher function is in a different scope. Try this:

var BackgroundColor = "red";
function ColorSwitcher ($) {
            //add red color to some classes via variable
}
jQuery(document).ready(ColorSwitcher);

jQuery(document).ready(function($) {
    $("ul.colors .color2").click(function () {
        BackgroundColor = "pink"; // change the color
        ColorSwitcher(); //run the function again to change colors of the classes with new color
        return false;
    })
});

That way it's in the top-level scope where it can be seen by the second invocation.

  • Related