0

My goal is to change the value of activeindex in each of the button elements based on a conditional statement. There are 5 buttons if the flag is true, and there should be 4 when false. However I need to calculate the activeIndexes basedon the condition, instead of them being hardcoded. Example: when the flag is off then the last button should have an activeindex of 3, not 4. I imagine I will loop or create a array but little stuck.

let flag = true;
let links = document.getElementsByClassName('link');

<button class='link' activeIndex={0} />
<button class='link' activeIndex={1} />
{#if flag}
<button class='link' activeIndex={2} />
{/if}
<button class='link' activeIndex={3} />
<button class='link' activeIndex={4} />
7
  • One question is why you need to use indices in the first place. Commented Aug 5, 2022 at 15:28
  • its a larger project (i didnt create it, just involved now). But one method i think might be using for loop and creating an array first.. I would have had it render a list of buttons with .map or somethings personally. Commented Aug 5, 2022 at 15:29
  • You also should try to avoid DOM queries like document.getElementsByClassName when using Svelte. Commented Aug 5, 2022 at 15:30
  • 1
    I don't know Svelte, but I'm guessing you just write exactly that, after initializing the variable to 0 at the beginning. Commented Aug 5, 2022 at 15:35
  • 1
    @Barmar Does not work like that, Svelte is declarative so you should not modify state during its template execution. Commented Aug 5, 2022 at 15:39

1 Answer 1

1

One really dirty fix would be to just add 1 conditionally (do not do this):

{#if flag}
  <button class='link' activeIndex={2} />
{/if}
<button class='link' activeIndex={2 + (flag ? 1 : 0)} />
<button class='link' activeIndex={3 + (flag ? 1 : 0)} />

With an array you can do something like:

<script>
    let flag = true;
    
    $: links = [
        { data: 'a', show: true },
        { data: 'b', show: true },
        { data: 'c', show: flag },
        { data: 'd', show: true },
        { data: 'e', show: true },
    ].filter(x => x.show);
</script>

{#each links as link, i (link)}
    <button>
        Button {link.data} Index: {i}
    </button>
{/each}

REPL

{#each} provides its own index, so you just have to add/remove the respective item to/from the array.

Sign up to request clarification or add additional context in comments.

1 Comment

I will probably go back and change the approach to this problem later but this works for svelty land!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.