Bonny
Bonny

Reputation: 202

Open popup/modal depending on setTimeout/Button Click using Javascript

I have 2 popups on the same web page.

  1. When someone clicks on the "Buy Now" link then "Buy Now Alert" should open. And I know this is working fine with onclick event.

  2. When the user does not click on the "Buy Now" button within X seconds (I am taking 5 seconds in my example) then the "Feedback Popup" alert should appear. I used setTimeout to show the popup but I don't want the "Feedback Popup" to show up if someone has already clicked on the "Buy Now" link.

Right now if I click on "Buy Now" then I am getting "Buy Now alert" and also getting "Feedback Popup" alert as well.

I want to show only one popup based on my action -> If I click on "Buy Now" then Buy Now alert and if I don't click the buy now link then by default "Feedback Popup alert"

How can I stop showing "feedback popup" on click of the "Buy Now" button? Help appreciated (Note: I tried clearInterval but no luck :'( )

function func1() {
  alert("Buy Now Popup");
}

const popup = document.querySelector(".popup");

window.onload = function () {
  setTimeout(function () {
    alert("Feedback Popup");
  }, 5000);
};
<header>
  <h1>Modal Popup</h1>
</header>

<div>
  <a href="#" class="modalButton" data-popup="popupOne" onclick="func1()">Model Popup</a>
</div>

Upvotes: 0

Views: 871

Answers (1)

Doron Mor
Doron Mor

Reputation: 71

This is a little example usage to what you described.

The blue background will appear in 5 seconds if you do not click the button, but every click on the button you will reset the time.

var btnTimeout = null;

function resetTimeout(){
  btnTimeout = setTimeout(() => {
    // do whatever you want to do when time comes
    document.body.style.background = "blue";
  }, 5 * 1000); // example of 5 seconds for faster response (change to 60)
}

function doSomething(){
  if(btnTimeout){
    clearTimeout(btnTimeout);    
  }
  
  resetTimeout();

  // do whatever you want to do when click the btn
  document.body.style.background = "red";
}

resetTimeout();
<button onclick="doSomething()">Buy now (prevent blue from showing)</button>

Upvotes: 1

Related Questions