javascript various backgrounds on click

I have implemented a list to allow users to select their top 3 choices, and I am using JavaScript to track these selections and change the background color accordingly.

1st selection -> Green background
2nd selection -> Yellow background
3rd selection -> Red background

JavaScript:

events: {
    'tap #achieveList li': "makeSelection"
  },

  makeSelection: function(e) {
    var radioBtn = e.target;
    var selected = this.el.getElementsByClassName('selected');

    if (radioBtn) {
      if (radioBtn.classList.contains('selected')) {
        radioBtn.classList.remove('selected');
      } else if (selected.length < 3) {
        radioBtn.classList.add('selected');
      }
      this.monitorSelections(selected);
    }
  },
  monitorSelections: function(selected) {
    if (!selected) return;

    var selection = [];

    for (var i = 0; i < selected.length; i++) {
      selection.push(selected[i].innerHTML);
    };

    ag.submit.data({
      label: "This is top 3",
      category: "User input",
      value: selection.join(','),
      valueType: "list",
      path: app.getPath(),
      unique: true
    });

  }

HTML:

<div class="interactive-block">
  <ul id="achieveList">
    <li>More engagements</li>
    <li>Cost efficiencies</li>
    <li>Better access</li>
    <li>Higher customer value/satisfaction</li>
    <li>Become more digital</li>
    <li>Better customer insights</li>
  </ul>
</div>

Answer №1

A) It seems like you don't actually need a library for this task:

let items = []

const $$listItems = document.querySelectorAll('li')
$$listItems.forEach($item => $item.onclick = () => {
  // Clear existing classes
  $$listItems.forEach($item => $item.className = '')
  // Add clicked item if not already in array
  if (!items.includes($item)) items.unshift($item)
  // Limit to maximum of 3 items
  if (items.length > 3) items.pop()
  // Apply CSS classes
  items.forEach(($item, index) => $item.classList.add(`bg${index + 1}`))
})

https://jsfiddle.net/my2tw36d/

Try the example above by clicking or tapping on list items to see if it meets your needs.

B) By making a simple adjustment to my previous code, you can achieve the desired outcome. Using a reversed array eliminates the need to modify how CSS classes are set.

// Add selection if not included
if (!items.includes($item)) items.push($item)
// Keep only 3 items at most
if (items.length > 3) items.shift()

https://jsfiddle.net/unatfyo5/

C) If you want to restrict selections after choosing 3 items, you can implement the following:

if (!items.includes($item) && items.length < 3) items.unshift($item)

https://jsfiddle.net/stLghxor/

I hope this explanation is helpful :)

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

Utilizing Express and ejs to display a JSON using the "<%" tag

I am facing an issue with the code in my index.ejs file. The current code snippet is as follows: var current_user = <%= user %> In my node.js file, I have the following code: app.get("/", function(req, res){ res.locals.user = req.user res. ...

Utilize Array in Form Input with Index and Spread Operator

Looking to create a form that can handle array data with dynamic fields in TypeScript. Encountering the following error: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ nam ...

Managing the clearance of an absolutely positioned div with CSS

I'm encountering an issue where my page contains divs that are 250px x 250px and positioned absolutely. When one of these divs is opened, an ajax call expands the div to display all its contents. These divs have a maximum width of 600px but can vary i ...

Right and left floating elements align side by side

The alignment of the images and file labels needs adjustment to ensure they all appear on the same line. Below is the code snippet that I have tried: HTML: <div> <img src="{{asset('bundles/cramifaccueil/images/pdfdocument.png')} ...

Does this extensive combination of pseudo classes hold true?

Here's the code snippet I am working with: .fontmenu .fontlist{ position: absolute; bottom:30px; display:none; } .fontbutton button:hover .fontmenu .fontlist{ display:block; } <div class="fontmenu"> ...

Steps for automatically playing the next song when a button is clicked

I have encountered a challenge in developing a music player. The issue lies in the loading of the next song when the user clicks the 'next' button. While the new data is successfully updated in both the state and render, the music does not automa ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Give a jQuery Mobile flipswitch a new look

Currently, I am using jQuery Mobile and recently attempted to refresh a flipswitch. However, upon executing the code $("#flipEnabled").slider("refresh");, I encountered an error in the console: Uncaught Error: cannot call methods on slider prior to initial ...

Retrieving user input in Angular and showcasing extracted keywords

I want to give users the flexibility to customize the format of an address according to their preference. To achieve this, there will be a text input where users can enter both keywords and regular text. The goal is to detect when a keyword is entere ...

Automatically resize ui-select dropdown box to the left side

I've been tasked with incorporating AngularJS ui-select into my project, specifically creating a multiselect dropdown. Currently, the dropdown box automatically adjusts its width based on the length of the longest selectable text, causing it to extend ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

Is it possible to utilize Jsoup to extract specific portions of JavaScript code from a webpage?

I am looking to extract data from the following script: $(document).ready(function(){ $("#areaName").val(1);$("#state").val(29);$("#city").val(1); $("#subareaName").val(1);$("#lane").val(1); } Specifically, I need to retrieve values such as areaName ...

Real-time monitoring within a callback function in Angular 5

I need to ensure that a specific callback is executed only after receiving a response, starting from the line this.groupDefaultExpanded = -1; onwards. loadLoginDetails() { this.derivativeSpecService.getDerivativeDetails().subscribe( res => ...

Extract the value from JSON data

I am faced with the challenge of extracting the value of slug from each child in a JSON dataset. The issue lies in the fact that I cannot predict how many children will be generated whenever new data is received. The generation of nested children is dynam ...

Change the color of the plotly button when it is clicked

I recently implemented a custom button on my plotly modeBar and I would like it to retain a distinct color when clicked. This would help visually indicate its "active" state, allowing users to easily discern whether it is enabled or disabled based on its ...

The markers from KML exported from My Maps are not showing up on the Google Maps JavaScript API

I have a map on Google My Maps that I want to showcase through the Google Maps JavaScript API. This way, I can easily merge multiple maps into one and add paths/markers without needing to code it all manually. Test out the map I'm using by clicking t ...

Managing numerous range sliders in a Django form

My Request: I am looking to have multiple Range sliders (the number will change based on user selections) on a single page. When the sliders are moved, I want the value to be updated and displayed in a span element, as well as updating the model. The Issu ...

Tips for expanding a text input field vertically, not horizontally like in Facebook, while typing or by holding down the Shift key and pressing Enter

I've come across numerous plugins that enable vertical resizing of a textarea and others that allow horizontal resizing of an input field. However, I have yet to find one that enables vertical resizing of an input field similar to Facebook's comm ...

Securely package tailor-made services within an application

Recently, I have been researching how to create custom services for AngularJS. However, all the examples I found demonstrate defining the service directly on my app using myApp.factory(...). For reference, you can check out the official docs for an example ...

Learning the best practices for incorporating publish and subscribe in Meteor JS is crucial for achieving efficient

I need some guidance on my implementation of publish and subscribe in Meteor JS. I am new to this and seeking help to ensure that I am doing it correctly. If you require more information about my code, I am happy to provide additional source code. Despit ...