Hot Chocolate

Is the hot chocolate the right temperature?

Skills: InputOutputVariablesIf Statements

This project introduces Svelte-specific if statements inside your HTML.

You can still write normal if statements inside the <script></script> tags, but you won't have to as often.

As with the previous projects, you'll use some Svelte-specific code in curly braces { }.

Specifically, we'll use the {#if}, {:else if}, {:else}, and {/if} to decide what HTML to have on the page.

Our demo is going to be a simple app that tells you if the variable is less, more, or equal to 2.

Let's compare the jQuery version of Is It More Than 2? with the Svelte version.

HTML & JavaScript (jQuery)

<label>
  Number:
  <input id="numInput" type="number">
</label>

<button id="btnCheck">Check</button>

<p id="txtResult"></p>
$('#btnCheck').click( ()=> {
  let input = $('#numInput').val()
  let number = Number(input)

  let result = ''

  if (number < 2) {
      result = number + ' is less than 2.'
  } else if (number > 2) {
      result = number + ' is more than 2.'
  } else {
      result = number + ' is 2.'
  }

  $('#txtResult').text(result)
})

Svelte

<script>
    let number = 0
</script>

<label>
  Number:
  <input type="number" bind:value={number}>
</label>

{#if number < 2}
  <p>{number} is less than 2.</p>
{:else if number > 2}
  <p>{number} is more than 2.</p>
{:else}
  <p>{number} is 2.</p>
{/if}

Project

  1. Look over the code below, think about how it runs, and compare the output with the source code.
  2. Create a new Svelte project from the template.
  3. In the terminal in VS Code, type npm install and then npm run dev.
  4. Check that your server is running by going to https://localhost:3000.
  5. Write an app that will take in a hot chocolate's temperature and tell you if it's tepid, good, or too hot.
  6. This line might help: <input type="range" min="0" max="100" bind:value={temp}>
  7. There's an exemplar below - try to avoid looking at it unless you get really stuck.
  8. Test your app in your browser.
  9. Commit your code with an appropriate message.

Sandbox

Feel free to play around with the example below to see how the web app reacts to your changes in a consequence-free environment.


Sandbox

Feel free to play around with the example below to see how the web page reacts to your code changes in a consequence-free environment. You won't break or overwrite anything so go for gold.