Ways to dynamically alter the appearance of a conditionally displayed element in Svelte

Currently experimenting with SvelteKit 1.0 by building a simple to-do app, but I'm having trouble implementing conditional text strikethrough. My goal is to have the text style change to include a strikethrough when the user clicks on the checkbox next to the TodoItem. Despite logging the values for completed and textDecoration whenever they're updated, everything seems to be passing correctly, yet the style does not update as expected.

I've gone through the documentation here, trying to follow it closely, but unfortunately, the functionality still isn't working. Here's the code snippet:

+page.svelte (Home)

<script lang="ts">
    import SearchBar from '$components/SearchBar.svelte';
    import TodoItem from '$components/TodoItem.svelte';

    let todos = [
        {
            id: 0,
            text: 'first task',
            completed: false
        }
    ];

    const addTodos = (taskText: string) => {
        if (!taskText) return;

        todos = [
            ...todos,
            {
                id: todos.length,
                text: taskText,
                completed: false
            }
        ];

        console.log(todos);
    };

    const checkTodo = (id: number) => {
        todos[id].completed = !todos[id].completed;
    };
</script>

<h1>to-do app</h1>
<SearchBar onAdd={(str) => addTodos(str)} />

{#each todos as todo}
    <TodoItem
        text={todo.text}
        bind:completed={todo.completed}
        onCheck={() => checkTodo(todo.id)}
        onDelete={() => console.log(`Delete ` + todo.id)}
    />
{/each}

TodoItem.svelte

<script lang="ts">
    export let text: string;
    export let onDelete: () => void;
    export let onCheck: () => void;
    export let completed: boolean;
    $: textDecoration = completed ? 'line-through' : 'none';

    // Logging when value changes
    $: textDecoration, console.log(textDecoration);
    $: completed, console.log(completed);
</script>

{#if text}
    <div class="todoContainer">
        <input
            on:click={() => {
                onCheck();
            }}
            id={`todo-checkbox-` + text}
            type="checkbox"
        />
        <div style:textDecoration style:textAlign="left">
            {text}
        </div>
        <div on:click={onDelete} on:keypress={onDelete}>x</div>
    </div>
{/if}

<style>
    .todoContainer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 50px;
        border: 1px solid black;
        border-radius: 5px;
        margin: 10px 0;
    }
</style>

Answer №1

When using the style:directive, remember to opt for dashes instead of camelCase (note that there may be a lack of examples in the documentation and tutorials).

style:text-decoration={textDecoration}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to create square editor tabs in Eclipse without using swt-border-radius?

The design of Eclipse's rounded and/or swooshing tabs is starting to feel outdated in today's modern era. I thought that by adding the following line in my default.css file, I could get rid of the rounded corners: swt-corner-radius: 0px Howeve ...

Firebase Error: In order to deploy without hosting via source, options must be provided. (app/no-options)

After developing a Next.js application, I integrated Firebase authentication and utilized the useContext hook for managing user state throughout the app. Here's the snippet of code for the AuthContext: auth.js import { createContext, useState, useEff ...

A step-by-step guide on customizing the background color of the selected date in the MUI DatePicker

I am looking to customize the background color of selected dates in a MUI datePicker. In the image below, you can see that I want to change the blue color to a different color. Here is my code: const customStyles = makeStyles(theme => ({ datePickerC ...

Do mobile CSS/HTML have distinct rules to follow?

I am having trouble displaying a background image in CSS. Additionally, I am unable to set a background color for a div. #mlogo { background-image: url(/mobileimages/2015LOGOFB.jpg); background-size: 100%; background-position: top; backgro ...

Is there a way to replicate the functionality of $(document).ready for dynamically loaded AJAX content?

$(document).ready(handler) is triggered once the DOM has finished loading. However, if new content containing a $(document).ready(handler) function is added to the page via AJAX, this function will be executed immediately according to the jQuery API. It&ap ...

Dynamic SVG positioning

Looking for a way to make this svg shape relative to its containing div? Fiddle: http://jsfiddle.net/8421w8hc/20/ <div> <svg viewBox="0 0 1000 2112" style="" xmlns="http://www.w3.org/2000/svg" version="1.1"> <path id="ma" st ...

The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login p ...

CoffeeScript's alert feature appears to be malfunctioning

After stumbling upon CoffeeScript in a blog post, I was excited to try it out. My first attempt at using it involved this code snippet: alert "Hello CoffeeScript!" Unfortunately, it didn't work as expected and produced the following error message: ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

Optimizing load behavior in React using Node.js Express and SQL operations

As someone who is fairly new to programming, I have a question regarding the connection between server and client sides in applications like React and other JavaScript frameworks. Currently, I am working with a MySQL database where I expose a table as an ...

Modifications made to the process module in one file are not reflected in a different file

It seems that the process module in NodeJS is not global, resulting in changes made to it in one module not reflecting in other modules. To confirm my findings, I wrote a small piece of code. Here is the snippet: server.js import app from "./app.js& ...

Tips for producing/reserving cropped images from a photo? (includes converting images to base64 format)

https://i.sstatic.net/6Nath.png Imagine having two square datasets taggedImages: { 0: {id:0, left:100, top:100, thumbSize:100, type: 'A', seasons: ['All', 'All']}, 1: {id:1, left:200, top:200, thumbSize:100, type: &apos ...

The CSS for SVG circles breaks in Firefox, causing the browser to strip away the radius property

Currently, I am working on creating a progress ring using SVG and CSS. It is functioning well in Chrome; however, Firefox (61.0.1 (64-bit)) is giving me trouble as it does not display the circle. I attempted to apply the method from this question but did n ...

Tips for sending data in Angular 8's Http GET method within a service class, especially when the backend requires a dictionary format

I am working on a C# backend with an HttpGet method that is expecting a dictionary as request parameters. public async Task<IActionResult> Search([BindRequired, FromQuery] IDictionary<string, object> pairs) Currently, my frontend is built in A ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...

How can I utilize the replace function in Angular to swap out a character?

I am attempting to change the characters { and } in an HTML string to {{ and }}. However, when using the replace function, I encounter the following error: $scope.selectedtemplate.template.replace is not a function Below is my code: $scope.selectedte ...

Ensure that useEffect is triggered before the render process is finished, or consider using an alternate method to achieve

How can I trigger functions to execute when state changes without waiting for the render cycle to complete and without using up memory with useMemo or useCallback? Is there a way to achieve this similar to useEffect, but more direct and efficient? ...

What causes observables stream to be cancelled or stopped by my HTTP request?

I am facing an issue with adding a new property called Blobs to each application in an array of applications. I need to make a separate HTTP request to fetch Blobs for each application using the switchMap operator. However, the problem is that only the las ...

Clicking on the anchor at the bottom of the page will smoothly navigate you to the top of the page

I added an anchor at the bottom of the page. I wrapped a group of buttons with the link so that when clicked, they trigger the assigned JavaScript and scroll to the bottom of the page. However, the buttons currently execute the JavaScript but then take you ...