Using a Svelte click event to toggle a boolean value in an array from a div

How can I modify the toggle functionality to work on any click event, not just on a button, in order to trigger a state change regardless of the element clicked?

ToolBar.ts

export default class ToolBar  {
    options:Array<ToolBarOptions>;
    constructor() {
        this.options = [
            new ToolBarOptions(ToolButton.sideMenu,SideMenuIcon,false,true, []),
            new ToolBarOptions(ToolButton.mainMenu,MainMenuIcon,false,true, [ new ToolBarOptions(ToolButton.export,exportIcon,true,true,[])]),
            new ToolBarOptions(ToolButton.entities,EntityIcon,false,true,[]),
            new ToolBarOptions(ToolButton.setting,settingsIcon,false,true,[]),
        ];
    }
}

class ToolBarOptions  {
    disabled:boolean;
    name:ToolButton;
    icon:string;
    show:boolean;
    options:Array<ToolBarOptions>;
    constructor(name: ToolButton,icon:string,disabled:boolean,show:boolean, options:Array<ToolBarOptions>) {
        this.name = name;
        this.disabled = disabled;
        this.icon = icon;
        this.show=show;
        this.options=options;
    }
}

export const enum ToolButton{
    mainMenu="mainMenu",
    export="export",

    entities="entities",
    sideMenu="sideMenu",
    setting="setting",
}

App.svelte

let toolbarOptions = new ToolBar();


function handleClickOutSide() {
console.log(toolbarOptions.options)
toolbarOptions.options.forEach((o) => {
o.show=!o.show;
});

console.log(toolbarOptions.options)
    <div  on:click={handleClickOutSide } class="toolbar">
  <ul class="">
    {#each toolbarOptions.options as  {name,  icon,options, show }, i}
    <li>
      
      <button on:click={()=>show=!show} name={name} class="flex items-center justify-center relative {toolbarOptions.options.length-1 === i ? "h-10":""}">
        {#if toolbarOptions.options.length-1 ===i}
        <div>100%</div>
        {/if}

        <icon>  {@html icon}</icon>
        <span>
          <svg fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-4 h-4">
            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5" />
          </svg>
        </span>

        {#if  options.length >0 }

        <div class="absolute top-10 w-32 bg-black h-10 cursor-pointer  {show ? "hidden":""}">
          <ul class="w-full flex">
            {#each options as  {name,  icon,show }}
            <li class="min-w-full flex items-center h-10 px-2">
                <span class="">  {@html icon}  </span>
                <span class="left-4 w-1/2"> {name}</span>
            </li>
            {/each}
          </ul>
        </div>
        {/if}

      </button>
    
    </li>
    {/each}
  </ul>
</div>

Answer №1

When dealing with items in a list, there are various options to consider for responsiveness:

  • Access item by index
  • Map through all items
  • Use a dummy assignment

Here are examples for each of these approaches:

let items = [
    { name: 'Item 1', checked: false },
    { name: 'Item 2', checked: false },
    { name: 'Item 3', checked: false },
];

const toggleViaIndex = () =>
    items.forEach((e, i) => items[i].checked = !items[i].checked);

const toggleViaMap = () =>
    items = items.map(item => ({ ...item, checked: !item.checked }));

const toggleViaDummyAssignment = () => {
    items.forEach(item => item.checked = !item.checked);
    items = items;
}

REPL

I personally don't prefer the use of dummy assignments as it may seem unnecessary. However, adding comments can help clarify the purpose of such statements.


Using classes should be avoided unless absolutely necessary, as they can interfere with certain functions or prototypes when working with methods like mapping where spread functionality is important.

Additionally, make sure to provide keyboard equivalents for non-button elements to ensure accessibility, such as an escape key press for click events.

Instead of toggling the visibility on click events, it's recommended to simply set show to false.


Regarding ToolBarOptions, you can greatly shorten the code using TypeScript:

class ToolBarOptions {
    constructor(
        public name: ToolButton,
        public icon: string,
        public disabled: boolean,
        public show: boolean,
        public options: Array<ToolBarOptions>,
    ) { }
}

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

Vue.js not populating select option tags

I've encountered an issue with my profie.html code that is intended to display division dropdown values using vue.js v-for and {{ val.division_name }}. However, the dropdown is rendering blank values even though there are supposed to be values present ...

Extract the Top X elements from a multidimensional array

Consider an Array that consists of nested arrays: [ ["2000-01-01", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a9a8abe091b6bcb0b8bdffb2bebc">[email protected]</a>", 1, 9, 338], ["2000-01-01", "<a href="/ ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

Utilizing WebView for Initiating AJAX Calls

One common question often asked is whether it's possible to make ajax requests using a webview. In my case, the UI will consist entirely of native Android code, but I still need to interact with the backend using ajax calls. Fortunately, I am well-ver ...

Is it possible that when a user is redirected to a different URL, Chrome terminates any pending Ajax requests?

Currently, I have a function that allows the user to unlock a list they are currently editing: function cancelLock(id) { $.ajax({ type: "POST", url: "/ajax.php?action=cancelLock", dataType: 'json', data: "id="+ id }); retur ...

Error Encountered When Updating cGridView in Yii: "TypeError: $.fn.yiiGridView is undefined"

I'm encountering an issue with updating the gridview TypeError: $.fn.yiiGridView is undefined; after using AjaxLink Click Button for Refresh <script> $(document).ready(function(){ $("#tombol_refresh").click(function(){ $.fn.yiiGridView ...

``Next.js allows you to nest components within a component to create routing functionalities

My login page has 3 different roles for logging in: Admin, Student, and Company. Instead of redesigning the entire page, I just want to update the login component for each specific role. Login Page export default function Authpage(){ return( ...

jQuery wordpress Error: $ function is undefined and not recognized

Having trouble using jQuery to disable checkboxes after selecting two options on a restaurant menu displayed in a modal. Despite trying various recommendations, I have not been successful in resolving this issue. Visit the URL for reference: Here is the ...

How to send arguments to a callback function in Next.JS

Here's the code snippet I'm working with: import Router from "next/router"; import React from "react"; export default function MainIndex() { return (<React.Fragment> <h1>Main Index Page</h1> ...

Avoid changing the format when sending a JSON string to Node

I am attempting to send JSON data to a Node application using a POST request, which will then be retrieved through a GET request. On the client side, I create a JSON string representing the model and send it to the server: $.post(serverURL, ko.mapping.toJ ...

Searching for a cake in CakePHP with autocomplete functionality

$( "#skills" ).autocomplete({source: function(request, response) { $.getJSON("http://server/current/indrealestates.com/properties/autosuggesthome/",{ term:request.term ,extraParams:$('#property_id').val()}, response ); }, ...

The Art of JavaScript Module Patterns in Image Sliders

I'm diving into the world of JavaScript and decided to try my hand at creating an image slider. I managed to put together a basic version by following a couple of tutorials, and although it's working fine, I want to move it to an external js file ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

Is it possible to utilize jQuery's .wrap or .wrapInner to encase a variety of elements within them?

I am working with a HTML structure that looks like this: <section> <item> <ele class="blue" /> <ele class="green" /> <ele class="red" /> </item> <item> <ele class="blue" /> <ele ...

One method for routing pages in React Router is to have a shared component that is displayed on multiple pages, as well as a

My app.js consists of multiple pages with the navbar and sidebar as components, but my login page is different and does not include these elements. How can I use react-router to create separate routes for the login page without the sidebar and navbar, whil ...

When preparing for production, SvelteKit's Static adapter appends `.html` to href links

I am currently utilizing SvelteKit with the static adapter, and I am facing an issue. Is there a way for me to modify the <a href="/otherPage".../> so that when I execute npm run build, the href includes the .html extension? Right now, af ...

Using a loop to execute Javascript Promise.all()

I am currently facing an issue where I need to make a web API call twice inside a loop, and then wait for the results before pushing them into a larger array as subarrays. The code snippet below illustrates my approach: var latlngPairs = []; function extra ...

Error Encountered (TypeError): Unable to access attributes of undefined (attempting to read 'appendChild')

I have been working on creating a choropleth Map of AntV using React.js with functional components. This is the code snippet for my chart: import DataSet from '@antv/data-set'; import { Chart } from '@antv/g2'; const CustomerByRegion = ...

What are the steps to generate two unique instances from a single class?

Is there a way to output two instances of the class Cat : Skitty, 9 years and Pixel, 6 years, in the console? (() => { class Cat { constructor(name, age) { this.name = name; this.age = age; } } docume ...

Performing a simulated click on a dynamically inserted element using pure JavaScript

I am faced with the challenge of programmatically navigating a ReactJS-based website in a looped workflow. The process involves clicking on Element1, dynamically altering the web page to add Element2, then clicking on Element2, and so on until eventually r ...