Fseee
Fseee

Reputation: 2631

jquery javascript avoid running function on condition

I've a set of jquery and generally javascript function in a js. Now I want to avoid some of the functions to be available on some condition. For example:

function test () {
    alert("hi");
}

function avoid () {
   if(condition)  {
     //here avoid to call test
   }
}

Thanks

Upvotes: 0

Views: 840

Answers (2)

Mehdi Karamosly
Mehdi Karamosly

Reputation: 5428

I am not sure if I understood your question well but if the call to your test function is within the avoid function like below:

function test () {
    alert("hi");
}

function avoid () {
   if(condition)  {
     //here avoid to call test
    return false;
   }
   test();
}

Then a simple return false could solve your problem, I am not sure if your functions are using events but if that is the case this is a good post that you can read about preventDefault and return false : enter link description here

if test is at the same level of avoid like below :

function test () {
alert("hi");
}

function avoid () {
   if(condition)  {
     //here avoid to call test
    return false;
   }
   return true;
}

// below is your functions call
   check =  avoid();

   if(check){
    test();
   }

This post explains how to exit from a function: enter link description here

I hope that helps.

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382092

If you want to remove a function without errors (provided the caller of the function doesn't expect a returned result), you might do

function avoid () {
   if(condition)  {
     test = function(){}; // does nothing
   }
}

Note that if your avoid function is in a different scope, you might have to adapt. For example if test is defined in the global scope, then you'd do window.test = function(){};

Upvotes: 1

Related Questions