Anpace
Anpace

Reputation: 117

Svelte on:click event

I'm new in developer and svelte and I'm trying to understand svelte/sveltekit doing simple roll dice game, pressing on roll dice button, dice image should change.

First of all I create a function who has supposed to get back an image based on random number

<script>
    let randomNumber = Math.trunc(Math.random() * 6) + 1;
    function rollDice() {
        let randomImage = `/src/lib/images/dice-${randomNumber}.png`;
        return randomImage;
    }
</script>

Then I insert img and button

<img src="/src/lib/images/{randomNumber}" alt="Playing dice" class="dice" />


<button on:click={rollDice} class="btn btn--roll">🎲 Roll dice</button>

Now when i press the button nothing happens and I can't understand what I didn't understand and what I'm doing wrong.

Upvotes: 1

Views: 2701

Answers (2)

Ruigats
Ruigats

Reputation: 1

You should have

Math.trunc(Math.random() * 6) + 1;

Inside de onclick event so it rolls to a random number every time you click to roll.

Should work if

<script>
let randomNumber = Math.trunc(Math.random() * 6) + 1;
function rollDice() {
    randomNumber = Math.trunc(Math.random() * 6) + 1;
    let randomImage = `/src/lib/images/dice-${randomNumber}.png`;
    return randomImage;
}

You'll maybe need to make it reactive too as the previous answer, but I don't think it'll need required.

Upvotes: 0

Shriji Kondan Elangovan
Shriji Kondan Elangovan

Reputation: 1109

You need to declare the randomNumber and randomImage as a reactive declaration.

The solution looks like this.

<script>
  $: randomNumber = Math.trunc(Math.random() * 6) + 1;
  $: randomImage = `/src/lib/images/dice-${randomNumber}.png`;
  function rollDice() {
       randomNumber = Math.trunc(Math.random() * 6) + 1
  }
</script>


<!-- <img src="/src/lib/images/{randomNumber}" alt="Playing dice" class="dice" /> -->

<p>
    randomNumber: {randomNumber}
</p>

<p>
    {randomImage}
</p>

<p>
    src = /src/lib/images/{randomNumber}
</p>

<button on:click={rollDice} class="btn btn--roll">🎲 Roll dice</button>

Upvotes: 0

Related Questions