bobthegoat2001 bobthegoat2001 - 5 months ago 16
Javascript Question

Have a buy button show up after 3 minutes, but instantly after second or greater page view (Javascript preferred)

I've already created a script that shows the buy button after 3 minutes, but I'd also like to add a feature on top of it that shows the button instantly if the person has already viewed the page before. I wasn't sure how to go about that part. Here's that I've got for the current timed buy button:

<script>
function timedBuyButton() {
document.getElementById("buyButton").innerHTML = "Buy Button";
}
</script>


I then make an empty div container with id "buyButton" where I buy button to show up. And lastly, I put the trigger in the body tag:

<body onload="setTimeout(timedBuyButton, 180000)">


Anyone have any ideas?

Answer

It's hacky, but this should get the job done:

<script>
  hereb4 = localStorage.hereb4;
  hereb4 = hereb4 === 'firsttime' || hereb4 === 'secondtime' ? 'secondtime' : 'firsttime';
  function timedBuyButton() {
    document.getElementById("buyButton").innerHTML = "Buy Button";
  }
</script>

<body onload="setTimeout(timedBuyButton, localStorage.hereb4 === 'secondtime' ? 0 : 180000)">

This sets a value to localStorage (note that you can only set strings to localstorage). This value persists across refreshes.

If you load the page for the first time, localStorage.hereb4 will be equal to undefined, which is not equal to 'firsttime'. Therefore, that ternary will set it to 'firsttime'. However, when you load the page the second time, localStorage.hereb4 will be equal to 'firsttime', and so the ternary will set it to 'secondtime'. Thereafter, it will always be equal to 'secondtime', and so set to 'secondtime'.

The ternary in your onload statement will just fire a timer with a interval of 0 if it sees 'secondtime' as the value there, otherwise it will count out your full 3 minutes.