Beginner in web coding, I have issue to code a sharing button that lead to whatsapp and that share a countdown. I achieve it with static string but I can’t load a variable in it…
Does someone know where my issue is please ?
<script> // Set the date we're counting down to var countDownDate = new Date("Aug 20, 2022 12:00:00").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); var countdown_iam = days + "j " + hours + "h " + minutes + "m " + seconds + "s " // Output the result in an element with id="countdown" document.getElementById("countdown").innerHTML = countdown_iam; // If the count down is over, write some text if (distance < 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "SURPRISE!!!"; } }, 1000); function openWhatsApp() { //var countdown_whatsapp = "test"; //alert(countdown_iam); window.open('whatsapp://send?text=' + countdown_iam); } </script> <h2> WhatsApp sharing Link </h2> <!-- create an image icon to open the WhatsApp onclick --> <img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()">
Thank’s for your help
Advertisement
Answer
The countdown_iam
variable is created within a function and only exists within that function. So when the other function (openWhatsApp
) tries to use the variable, it can’t find it and the error occurs.
You want to access the countdown string from two different functions, so one option would be to create a new function that makes the countdown string and returns it. You can then call that function from both places. I’ve done that here:
<script> function getCountdown() { var countdownDate = new Date("Aug 20, 2022 12:00:00").getTime(); var now = new Date().getTime(); var distance = (countdownDate - now) / 1000; if (distance < 0) { return 'SURPRISE!!!'; } else { var days = Math.floor(distance / (60 * 60 * 24)); var hours = Math.floor((distance % (60 * 60 * 24)) / (60 * 60)); var minutes = Math.floor((distance % (60 * 60)) / 60); var seconds = Math.floor(distance % 60); return days + "j " + hours + "h " + minutes + "m " + seconds + "s "; } } function openWhatsApp() { alert('whatsapp://send?text=' + getCountdown()); } setInterval(function() { document.getElementById("countdown").innerHTML = getCountdown(); }, 1000); </script> <h2>WhatsApp Sharing Link</h2> <p id="countdown"></p> <p><img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()"></p>