A Stimulus (JS) “List” Controller

  • up /down/remove— put these on the buttons that will reorder the items or remove items.
  • add — put this on the button that will add a new item
  • data-list-list-item-template-id — the id of your <template>. Upon add, the HTML inside the template will be copied to create your new list item.
  • up/down/remove—put these on the buttons that will reorder the items or remove items. The target attribute must be given to the same element as the up/down/remove action attributes.
  • listItem — the wrapper for your list item. This is the element that gets moved around.
  • container — the direct parent of the listItems. container must contain no other children. (To get rid of this requirement, you can modify the controller to use this method)
const application = Stimulus.Application.start()application.register(“list”, class extends Stimulus.Controller {
static get targets() {
return [“up”, “down”, “remove”, “listItem”, “container”]
}
up(event) {
const index = this.upTargets.findIndex(t => t === event.target);
const listItemElement = this.listItemTargets[index];
listItemElement.previousElementSibling.insertAdjacentElement(‘beforebegin’, listItemElement);
}
down(event) {
const index = this.downTargets.findIndex(t => t === event.target);
const listItemElement = this.listItemTargets[index];
const nextListItemElement = listItemElement.nextElementSibling;
nextListItemElement.insertAdjacentElement(‘afterend’, listItemElement);
}

remove(event) {
const index = this.removeTargets.findIndex(t => t === event.target);
const listItemElement = this.listItemTargets[index];
listItemElement.remove();
}
add(event) {
const templateId = this.data.get(“listItemTemplateId”);
const template = document.getElementById(templateId);
this.containerTarget.appendChild(template.content.cloneNode(true));
}
});

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introduction to the Jest and Puppeteer Timeouts

All about JSX

Accessing Google Cloud Storage Bucket’s using AWS SDK

Build Faster Web Applications with Angularjs

Build Faster Web Applications with Angularjs

Next.js SSR vs. SSG & Incrementalism

The technology revolution is unstoppable, and there has been continuous development to make the…

Getting Started with React Native on MacOS

Stripe Checkout Integration with Angular

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dylan Phan

Dylan Phan

More from Medium

INTRODUCTION

The Project Ara Fumble

Earning Mechanism of Horizonland

My Swarm App Attracts Large-Scale Issuance