5

I created a simple countdown with Alpine JS, but when timer is 0, I have an error. First declare in x-data the function appTimer.

 <div x-data="appTimer()">
    <div x-show="active">
        <template x-if="countdown > 0">
            <div>
                <div>Counting down</div>
                <div x-text="countdown"></div>
            </div>
        </template>
        <template x-if="countdown === 0">
            Countdown completed!
        </template>
    </div>
</div>

This code JS, here set active, countdown and window.setInterval.

 <script>
    function appTimer()
    {
        return {
            active: true,
            countdown: 5,
            init() {
                window.setInterval(() => { 
                  if(this.countdown > 0) this.countdown = this.countdown - 1; console.log(this.countdown)}, 1000)
            }
        }
    }
</script>

enter image description here

Progman
  • 16,827
  • 6
  • 33
  • 48
Alexd2
  • 1,044
  • 2
  • 15
  • 28

2 Answers2

5

The issue is that you're putting text in the template instead of html, alpine tries to get the html defined in the template but doesn't find any so it gets confused, to fix the issue you simply need to wrap your message in an html element, such as:

<template x-if="countdown === 0">
  <div>Countdown completed!</div>
</template>

see this stackblitz reproduction

Dario Piotrowicz
  • 951
  • 1
  • 6
  • 14
0

I think it depends on your compare. You compare strict but i dont know if countdown is an integer. Try to compare with ==

<template x-if="countdown == 0">

Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79