Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

create array based on number of html elements

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} />

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading