I need to place a countdown timer within a sentence

Hi. So what I’m looking to do is place a countdown timer within a sentence.

“I currently live in West Fairview, Pennsylvania, USA with my soon-to-be-husband (timer_goes_here).”

I would like the timer to go within the parenthesis and change “soon-to-be-husband (timer_goes_here)” to “husband” after the timer has stopped…

I am terrible at Javascript and will probably need a good breakdown of the code to understand it.

(This question is very nearly the same as the birthday/age question you asked in another thread. Read the answer in that one, then give this a try to see if you understand the theory.)

1 Like

I would use date-time in a span, so that even when JavaScript isn’t available it still works and makes sense.

<p>I currently live in West Fairview, Pennsylvania, USA with my soon-to-be-husband
   <time datetime="2018-11-18 14:00:00" class="countdown">Nov 18 2:00pm></time></p>

And you can then hide parts of it by wrapping them with a span that JavaScript can then hide until the marriage has occurred.

<p>I currently live in West Fairview, Pennsylvania, USA with my
   <span class="hide adduntil" rel="married">soon-to-be-</span>husband
   <span class="hide adduntil" rel="married">
       <time ref="married" datetime="2018-11-18 14:00:00" class="countdown">Nov 18 2:00pm</time>
   </span>.
</p>

The rest of it is just checking if the married date hasn’t yet elapsed, so that you can remove the hide class from those adduntil elements and do a countdown on the date.

1 Like

If she keeps needing a countdown timer, can’t she create a generic timer, then customize it for each instance? Or does this require a new script each time?

For example, take this code…


Put it in a scripts folder, then each time she needs it, call it and change some code to fit her needs?

I been so busy learning software development, I’ve forgotten so much about JavaScript. I even had to scrap my own website so I can update coding standards.

Well then, that countdown timer can then be used with this basic code here:

function showNearlyMarried() {
    document.querySelectorAll(".adduntil[rel=married]").forEach(function (el) {
        el.classList.remove("hide");
    });
}
function countdown(el, datetime) {
  // use code to countdown from here
  console.log(el, datetime);
}
var el = document.querySelector("time[ref=married]");
var datetime = new Date(el.getAttribute("datetime"));
var now = new Date();
if (now < datetime) {
    showNearlyMarried();
    countdown(el, datetime);
}
.hide { display: none; }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.