1

I am trying to show an Ad when user scrolls less than 57% but tries to close/switch the browser tab. This is all my JS till now. And also, is there a way to have 1 iteration of the given modal, and only to show it on page refresh. I tried with window.onbeforeunload but it doesn't seem to be working.

// Modal

window.addEventListener("scroll", (e) => {
  let rootElement = document.documentElement;
  let scrollTop = rootElement.scrollTop;
  let pageHeight = rootElement.scrollHeight;
  let getPercent = (scrollTop / (pageHeight - rootElement.clientHeight)) * 100;
  if (getPercent >= 57) {
    document.querySelector(".modal").style.display = "block";
  }

  console.log(getPercent);

  window.onclick = function (e) {
    if (e.target == document.querySelector(".modal")) {
      document.querySelector(".modal").style.display = "none";
    }
  };
});
document.getElementById("close").addEventListener("click", (e) => {
  e.preventDefault();
  document.querySelector(".modal").style.display = "none";
});

function showAd() {
  return (document.querySelector(".modal").style.display = "block");
}
  • Jovan Jovanović went from being a poet, to developers, congrats :) – aca Jun 14 '22 at 12:02
  • Does this answer your question? [Is it possible to detect when the mouse is over the browser tab?](https://stackoverflow.com/questions/29747898/is-it-possible-to-detect-when-the-mouse-is-over-the-browser-tab) – Justinas Jun 14 '22 at 12:07
  • @aca Saw that being a poet doesn't pay as much as being a developer xD – Jovan Jovanovic Jun 14 '22 at 12:23

0 Answers0