Leo Hwang
Leo Hwang

Reputation: 3

How to run alert only once within range in if statement?

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100){
  $(".treat-button").one("click", function(){
    alert(petInfo.name + " is going obese...");
  });
 }
}

Here basically what I want to do is to display the alert only once when the petInfo.weight is equal or over 100 and stop alerting every time after I click on the treat-button. I have tried to look for the answer and tried everything I could but it's not working... Please help me good code masters!!

Upvotes: 0

Views: 383

Answers (4)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92337

I run your code and it actually wokrs fine - so probably the reason is that you run sendWeightAlert() again after button click (which bind event handler again - and show alert after next click)

let previousWeight= 10;
let petInfo = { weight: 100, name: 'dog' };

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100){
  $(".treat-button").one("click", function(){
    alert(petInfo.name + " is going obese...");
  });
 }
}


sendWeightAlert();  // here we bind handler only once, and jQuery `one` will run it once.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="treat-button">click me</button>

Upvotes: 0

vmf91
vmf91

Reputation: 1937

var alerted = false;

var previousWeight = 99

var petInfo = {
  weight: 101,
  name: 'petName'
}

$(".treat-button").one("click", function(){
  if(!alerted && petInfo.weight >= 100 && previousWeight < 100){
    alerted = true;
    alert(petInfo.name + " is going obese...");
  }
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<div class="treat-button" style="width: 100px; height: 100px; background-color: red;">TREAT</div>

Upvotes: 0

brk
brk

Reputation: 50291

You can create a variable and check its state before showing the alert

let showAlert = true;
$(".treat-button").click(function() {
  if ((petInfo.weight >= 100 && previousWeight < 100) && showAlert) {
    alert(petInfo.name + " is going obese...");
    showAlert = false;
  }
});

Upvotes: 1

Jaydeep Galani
Jaydeep Galani

Reputation: 4961

How about declaring a global variable by default true,

make it false when you execute alert.

and add it in your if condition.

var isAlertShown = true;

and your function,

function sendWeightAlert(){
 if(petInfo.weight >= 100 && previousWeight < 100 && isAlertShown){
  $(".treat-button").one("click", function(){
    isALertShown = false;
    alert(petInfo.name + " is going obese...");
  });
 }
}

Upvotes: 0

Related Questions