Tips on attaching a class to elements in a loop when a click event occurs

In my HTML, I am displaying information boxes from an array of objects that are selectable. To achieve this, I bind a class on the click event. However, since I am retrieving the elements through a v-for loop, when I select one box, the class gets bound to all of them.

Is there a way to differentiate only the selected box?

I have come across examples using jQuery, but I am interested in exploring other methods.

Here is my template:

<div class="list-services">
  <div class='column-service' 
    v-for='estimation in filteredEstimation' 
    v-bind:key="estimation.name" 
    :class="{ focusService }" 
    @click="focusService = !focusService"
  >
    <div class="service-name">
      {{estimation.name}}
    </div>
    <div class="service-description">
      {{estimation.description}}
    </div>
    <div class="service-price">
      {{estimation.price}} 
      <span class="price-currency">€</span>
    </div>
  </div>
</div>

Thank you for your time and assistance!

Answer №1

While attempting to create a jsfiddle to address your query, I stumbled upon a jsfiddle in the vue.js forum that might be useful: https://jsfiddle.net/mogtfpze/2/

This particular jsfiddle presents three distinctive options for highlighting content through clicks.

li v-for="item in items" 
  :class="{highlight:item.id == selected}" 
  @click="selected = item.id">
  {{item.id}}
</li>

Even though it's an older solution, I believe it should still function with the current Vue version.

If it doesn't work or if there are any uncertainties, feel free to reach out and I'll do my best to assist!

Answer №2

One technique that I personally employ (assuming I've grasped your question accurately) involves utilizing the this keyword.

For instance:

index.html

<ul id="myList">
    <li>a</li>
    <li>b</li>
    <li>c</li>
</ul>

script.js (Vanilla JavaScript)

var myList = document.getElementById("myList");
    myList.addEventListener("click", function () {
    console.log(this);
    console.log(this.innerText);
});

script.js (jQuery)

var myList = $("#myList").on("click", function() {
    console.log(this);
    console.log(this.innerText);
});

By using the this keyword in this manner, we can access the innerText of the clicked li element by simply attaching the event listener to the parent element. This is just one way to leverage the power of the this keyword - there are many other possibilities to explore by logging this in your event listener function.

Please let me know if this explanation proves 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

Why does the styling of the inner Span adhere to the style of the outer Span?

How can I adjust the opacity of the color "blue" to 1 in the code snippet below? <!DOCTYPE html> <html> <body> <p>My mom's eyes are <span style="color:blue;font-weight:bold;opacity:0"> <span style="color:blue;fo ...

Difficulty displaying Vue components

Having inherited a troublesome codebase, I am facing an issue where the Vue components fail to load. The Vue framework seems to be mounting, but the components are not being displayed. This Laravel 5.7 application integrates blade templates with Vue elem ...

Leveraging Parameters in Ajax with jQuery and JavaScript

I've been exploring jQuery and trying to update a specific TD element with innerHTML. However, I'm stuck on how to capture the value of a parameter. In this scenario, my goal is to grab the user-id "1234" in order to update the TD identified as ...

Having difficulty converting a local variable into a global variable in JavaScript and Express

I am facing challenges trying to convert a local variable into a global variable while working with Express and Javascript. Below is my JavaScript code snippet: // Setting up Express and EJS const express = require("express"); const JSON = requi ...

Showing identification on the drop-down list

Within my dropdown menu setup, I am aiming to achieve a specific functionality. When the user clicks on sub menu, I want the title of sub menu to display in the Menu space as illustrated below. What steps can be taken to accomplish this? UPDATE: After fu ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

Creating a peaceful web platform with React that supports several user roles

I am in the process of developing a single-page web application that must be completely restful, which is new territory for me. One challenge I'm facing is determining how to efficiently render the user interface for different roles using React. With ...

What is the best way to make a select tag read-only before the Ajax request is successful

Is there a way to make a select tag read-only before an Ajax success? I tried using this code, but it didn't work: $("#tower").prop('readonly', true); Then I tried this alternative, but I couldn't get the value from the select tag: ...

Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfi ...

Customize the bootstrap carousel to show multiple slides at the same time

I am looking to customize the bootstrap 3 carousel in order to show multiple slides at once. I understand that I could place several thumbnails in a single slide (div .item), but the issue is that the carousel will progress through them all at once, moving ...

AngularJS - Creating a dynamic wizard experience using UI-Router

I have set up my routes using ui-router in the following way: $stateProvider .state('root', { url: "", templateUrl: 'path/login.html', controller: 'LoginController' }) .state('basket&a ...

Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay). My issue arises from ...

Is there a different method similar to Textfield onChange that works like the HTML onChange attribute?

In my current setup, I have a Textfield component nested within other components where I pass a function pointer down to it as a prop. The challenge I'm facing is that the function responsible for passing the contents of the Textfield back up to the r ...

The Mui Switch track color fails to change when checked

I'm looking to customize the colors of the track for both checked and unchecked states. Currently, the track color is working for the unchecked state but defaults for the checked state: Checked State: https://i.stack.imgur.com/eGV4a.png Unchecked S ...

Update an API call to switch from promises to observables, implementing axios

Recently, I have been experimenting with using rxjs for API requests in a React application and this is the approach that I have come up with. What are your thoughts on this method? Are there any best practices that you would recommend following? If you ...

I'm having trouble modifying the backdrop to 'true' or removing it after setting it to 'static' in Bootstrap. Can anyone help me troubleshoot this issue?

I have been encountering an issue with changing the backdrop setting from 'static' to 'true' in Bootstrap modal. Here is the code I am using: $('#modal').modal({backdrop: 'static', keyboard: false, show: true}); ...

Showing information retrieved from an API and rendering it on an HTML page

My aim is to showcase a list of calculated results fetched from a local server. In the console, this data appears as an array of objects, but on the webpage, it is being displayed as separate string characters for each li element. How can I display the con ...

Center the panel on the page and decrease its width using Bootstrap

I recently incorporated a Bootstrap panel above a search results table - my first experience working with Panels. This panel contains a form with a select menu, allowing users to filter the list of search results based on their selections. Currently, the ...

Monitoring changes within the browser width with Angular 2 to automatically refresh the model

One of the challenges I faced in my Angular 2 application was implementing responsive design by adjusting styles based on browser window width. Below is a snippet of SCSS code showing how I achieved this: .content{ /*styles for narrow screens*/ @m ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...