Home > OS >  How to show a div only sometimes randomly?
How to show a div only sometimes randomly?

Time:09-23

I am trying to make my own subscription opt-in pop-up in HTML on my website. I want the pop-up to show only sometimes randomly. I don't want it to be visible all the time. I want it to be visible 1/3rd of the times. Please help me how to do it. I looked up on the web but it always misunderstood my question, so I am posting it here. Here is the code:

<div id="demo-float" class='demo-float'>
  <span class='df-hide'>
    <i class='fas fa-times'></i>
  </span>
  <div class='df-logo'></div>
  <h3>Subscribe</h3>
  <p class='excerpt'>Would you like to receive notifications on latest updates from Usual Queries?</p>
  <a href='https://usualqueries.blogspot.com/p/subscribe.html' title='Sub'>Subscribe</a>
</div>

Here is the link to that pop-up (i.e. my website): https://usualqueries.blogspot.com/

CodePudding user response:

You can achieve what you want by using the visibility property of your element and the setInterval() function, alongside Math.random(). You can use something like this:

let my_div = document.getElementById("my-div");

setInterval(() => {
  if (Math.random()<=0.33) // Chance = 1/3
    my_div.style.visibility === "hidden" ? my_div.style.visibility = "visible" : my_div.style.visibility = "hidden"; // If the element's visibility is set hidden, then set it back to visible and vice versa
}, 1e3); // Set the frequency of this interval to every 1 sec (1*10^3 ms)
<html>
<head>
</head>
<body style="background-color:grey">
  <div id="my-div" style="background-color:red">
    <p>This is my div</p>
  </div>
</body>
</html>

CodePudding user response:

Good day!

There are many ways you can go at this. Most of the times when randomness is involved in html5 family, javascript Math.random method is used. To use javascript in your html file, create a script tag.

<!--place the script tag in your head section-->
<script type="text/javascript">
    function popupForThisUser(){     
        setTimeout(popupRandom,5000); //first arg calls function second arg is time in miliseconds
    }
    function popupRandom(){      //this gets called by setTimeout
        var random = Math.floor(Math.random() * 100)   1; //integer between 1-100;
        if(random < 30){ //Logic for popup chance 
            return myPopup()  //return your popup
        }
    };
</script>  <!--close script-->
<body onload="popupForThisUser()">  <!--call to your initial function-->

With a function like this you could set the chance for a popup to show up after 5 seconds to 30%. I hope this is clear to you!

CodePudding user response:

If you want to have a defined interval of showing the div per user, you are going to need to access some form of storage in the browser, like indexedDB or cookies. Then you can iterate over the storage on every page load and if it matches the number of visits, you can choose to show the div.

  • Related