The syntax error in the Svelte conditional element class is causing issues

Trying to create an if block following the Svelte Guide for if blocks. The process appears straightforward, yet Svelte is flagging it as a syntax error:

[!] (svelte plugin) ParseError: Unexpected character '#'
public\js\templates\works.html
3:     <div class="slides js_slides">
4:       {#each works as work, index}
5:         <div class="js_slide {#if index === currentIndex }selected{/if} {#if index === 0 }first{/if}">
                                ^
6:           <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
7:         </div>

Why isn't {#if index === currentIndex } considered valid? How can I implement conditionals in Svelte?

I could potentially set up individual class= definitions for every potential outcome, but that would require extensive effort.

Answer №1

Blocks such as {#if..., {#each..., etc., cannot be inserted within attributes, as their function is solely to shape the structure of your markup.

As an alternative, it is customary to utilize ternary expressions...

<div class="
  js_slide
  {index === currentIndex ? 'selected' : ''}
  {index === 0 ? 'first' : ''}
">
  <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
</div>

...or employ a helper:

<!-- language: lang-html -->

<div class="js_slide {getClass(work, index, currentIndex)}">
  <img src="/images/work/screenshots/{ works[index].slug }-0.{ works[index].imageExtension }"/>
</div>

Some individuals opt to use constructs like

data-selected={index === currentIndex}
and data-first={index === 0}, then style elements based on [data-selected=true] selectors instead.

Answer №2

Starting from Svelte 2.13, it is also possible to use the following syntax:

<div class:selected={index === currentIndex}>...</div>

For more information, check out

Answer №3

As mentioned in the Svelte documentation, an additional JavaScript variable is required to handle if-else statements within a class.

Here's an example where an each loop iterates from a to b, and when the if condition is true, the specified CSS will be applied:

{#each Array.from(Array(b+1).keys()).slice(a) as i }

    <div class="{ i===4 ? "border-l-2 border-blue-500" : ""}  p-3 space-y-4">
     some sample text
    </div>
{/each}

Example (1 to 15):

{#each Array.from(Array(15+1).keys()).slice(1) as i }

    <div class="{ i===3 ? "border-l-2 border-blue-500" : ""}  p-3 space-y-4">
     some sample text
    </div>
{/each}

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 process of incorporating a lowercase normalizer into an Elasticsearch mapping object?

I'm attempting to incorporate a normalizer with a lowercase option into my mapping object, as detailed in the official Elasticsearch documentation Below is an example of my mapping object: const schema = { date: { type: 'date' ...

What could be causing the issue with Hindi text not displaying properly on Safari?

I'm having trouble with displaying Hindi text on my website. I tried pasting the text in a new file and it worked, so why is it not loading correctly in this case? The Hindi script is within the second span with the class word w2. "use strict"; le ...

Jstree's select_node function is failing to trigger

I am having an issue with the select_node.jstree function not firing properly. Below is the code snippet: $(document).ready(function () { //$("#MySplitter").splitter(); setupSplitter(); $("#divJsTreeDemo").jstree({ "themes": { "theme": "d ...

Error in identifying child element using class name

I need help accessing the element with the class "hs-input" within this structure: <div class = "hbspt-form".......> <form ....class="hs-form stacked"> <div class = "hs_firstname field hs-form-field"...> <div class = ...

Unable to locate the "fcm-node" module in Node.js with TypeScript

When working on a TypeScript project, I usually rely on the fcm-node package to send Firebase push notifications in Node.js. However, this time around, I faced an issue. I know that for TypeScript projects, we also need to install type definitions (@types ...

Issue encountered with Tailwind Color Classes not functioning correctly when triggered by a button click within NextJS and React Vite framework

Recently, I've developed a component showcasing the "Text Gradient" effect in Tailwind + React. The component comprises of 4 select dropdowns and a "randomize" button. Upon clicking the button or selecting an option from the dropdowns, the changes are ...

Modify animation trigger when mouse hovers over

I am looking to create a feature where a slide overlay appears from the bottom of a thumbnail when the user hovers over it, and retracts when the user is not hovering. animations: [ trigger('overlaySlide', [ state(&ap ...

React is a powerful tool that allows for the dynamic changing of state within

Struggling with my first React app and trying to accomplish something basic. The Input component in my app has an array in state, which sends two numbers and a unique ID as an object to a parent Component when the array has two numbers entered. Sending t ...

Leveraging Ajax with Google Analytics

Currently, I am working on a website that utilizes Ajax calls to update the main content. In order to integrate Google Analytics tracking code using the async _gaq method, I need to push a _trackPageview event with the URI to _gaq. There are two approaches ...

Struggling with a Bootstrap v5.0.2 Modal glitch? Let's dive into a real-life case study to troub

I am seeking assistance with a problem that I am encountering. I am currently using Bootstrap version 5.0.2 (js and css). Despite coding all the required parameters, I am unable to make the modal functionality work. I have been trying to figure out what&ap ...

"Optimize your website by incorporating lazy loading for images with IntersectionObserver for enhanced performance

How can I use the Intersection Observer to load an H2 tag only when the image is visible on the page? Here is the JavaScript code I currently have: const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObser ...

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

Rotating elements in CSS using the transform property with rotateX and rotateY values

I've created a transformation effect using CSS, and now I'm looking to start with a specific rotation (rotateX(15deg) rotateY(180deg)) and then animate it back to its original position. Is there a way to achieve this reversal effect and how can i ...

Passing Data from $http.get to Angular Controller Using a Shared Variable

One issue I'm facing is the inability to pass the content of a variable inside $http.get() to the outside scope, as it always returns undefined. I attempted using $rootScope, but that approach was not successful. controller('myControl', fu ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

Ways to deactivate remaining buttons until a function call finishes after selecting one in a react render() function?

In order to prevent the overlap of results when multiple buttons are clicked simultaneously, I need to disable all toggle buttons until one function call is complete, including the reset button. Additionally, I'm looking for a way to display my functi ...

Setting a pre-selected value in a Vue.js dropdown list involves a few simple steps. This

Currently, I am developing two Vue components. I am sending array data from the parent component to the child component using props. Now, I have a requirement to pre-select a value in the dropdown list of the child component. Below is a snippet of my code ...

Unable to perform surveillance on the htpp.get method

Example snippet: if (!this.scope.popupHtmlTemplate) { this.$http.get("widgets/pinpointcomponent/browseLibraries/resources/browseLibrariesDialogModal.html") .success((data: any) => { console.log("Processing success"+data) if (dat ...

Guide on customizing a dropdown button in a class-based Angular library with version 4 or higher

My dilemma revolves around utilizing the Angular Material library for a drop-down navigation bar. The issue at hand is my desire to hover through the list, yet I am unable to tweak the style within HTML. Fortunately, I can easily make alterations in Chrome ...

Discovering the following element containing an ID attribute with jQuery

Upon clicking a link, my goal is to locate the subsequent <section> with an ID attribute and retrieve its ID. In the provided code snippet and JavaScript function, the expected outcome upon clicking the link is for "section_3" to be logged in the co ...