0

Here is a simplified version of the problem.

Clicking on the button I need to call function abc and stop to execution both functions abc and click if x == 5;

Current situation - abc is canceled, but click continues to execute.

function abc(){
if(x == 5){return;}
console.log('abc');
}

var x = 5;

$('button').on('click', function(){
abc();
console.log('clicked');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>CLICK</button>
Liam
  • 27,717
  • 28
  • 128
  • 190

2 Answers2

1

If I'm understanding you correctly you just need to return a result from abc and test for it:

function abc(){
  if(x == 5){
    return false;
  }
  console.log('abc');
  return true;
}

var x = 5;

$('button').on('click', function(){
    if (abc()){
       console.log('clicked');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>CLICK</button>

BTW you should avoid defining global variables (x) like this. Instead use a closure to define a scoped variable. Something more like:

var closure = function(){
  function abc(){
     if(x == 5){
        return false;
     }
     console.log('abc');
     return true;
   }

  var x = 5;
  
  return {abc:abc};
}();

$('button').on('click', function(){
    if (closure.abc()){
       console.log('clicked');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>CLICK</button>

This is called the Revealing module pattern

Liam
  • 27,717
  • 28
  • 128
  • 190
  • what is the purpose of `closure`, pls? –  Dec 07 '18 at 10:38
  • Read the [link I posted](https://stackoverflow.com/questions/2613310/ive-heard-global-variables-are-bad-what-alternative-solution-should-i-use) in the answer and also the [link in that question](http://wiki.c2.com/?GlobalVariablesAreBad) @puerto – Liam Dec 07 '18 at 10:39
1

As an answer to stopping the click from performing any further unwanted actions (for example to stop a form submitting if your button was a "submit" button in a form, or to stop a link from actually visiting the URL of the link), you'd want to use the event's preventDefault() method:

function abc() {
    console.log('abc');
}


$('button').on('click', function(e){
    if(x == 5) {
        e.preventDefault();
        abc();
    }
    console.log('clicked');
});

var x = 5;
markmoxx
  • 1,492
  • 1
  • 11
  • 21