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

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Loading 3D models in Three.js from the cache

Every time my page reloads, the loader loads objects from the URL instead of cache. Is there a way to check if the resource is in cache and load it directly? Appreciate your help! ...

Having trouble generating a Vue project using vue/cli?

I am currently developing a vuex application using Vue CLI. Unfortunately, the CLI gets stuck during metadata fetching (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb88838480828f8a99abd9c5dac5dd">[email protected]</a& ...

"Encountering a halt in my Node.js Application as it waits endlessly

I'm currently following a tutorial on creating a collaborative canvas drawing application using Node.js and Socket.io. I've included the source file below which is used to create the server. However, when I try to open it in my browser, it gets s ...

How can I implement a page switch in vuejs by clicking on a name in a table list?

I'm currently working on a list page in VueJS and facing some challenges. Here is the code snippet: <template> <vue-good-table :columns="columns" :rows="row" :search-options="{ ...

Issue with Vuex: Error encountered while sorting the local Array

My Vuejs and Vuex-based app contains numerous files with utility functions and logic. Within one of these files, there is a function that returns promises and performs array manipulations: function firePixels (clientId, result) { return new Promise((re ...

What is the process of setting up a subelement in a Vue array?

I am currently working on incorporating an array read feature using Vue.js: {{ this.locations[this.record.carton.LocationID - 1].Location }} Although the code functions properly during runtime, it throws an error upon initial loading: app.js:55125 [Vue wa ...

Record the marker's location only once following the completion of its dragging action

Is there a way to make the console log for getPosition only happen when the marker is stopped being dragged, rather than every 0.1 seconds while it's being dragged? Similar to how .getRadius() works - it logs the radius change just once. https://i.ss ...

What is the best way to create a test for my Vue component using Jest?

Below is the login form component that needs to be tested for various scenarios: Verify successful login with both username and password filled Check for input error when either username or password is left blank Ensure input error is thrown when only us ...

Error: It is not possible to define the 'words' property of an undefined value

In my Vuex store, I have the following action: loadExercises ({commit}) { commit('setLoading', true) const db = firebase.firestore() db.collection('exercises').get() .then(querySnapshot => { const exercises = [] ...

What are the reasons behind the unexpected behavior of the replace() method in the newest Safari update?

What is causing the JS method replace() to behave incorrectly in Safari version 11.1 when using "$<" in the second argument? For example: "aaaXXXbbb".replace(/XXX/, '_before_$<_after_') The actual result is: "aaa$<_after_bbb" The ex ...

NextJS is like the master of ceremonies in the world of backend

As I was searching for the top JS backend frameworks, I came across NextJS which is considered to be one of the best. Initially, I thought NextJS was just a simplified version of CRA and still required Node.js as the backend. This brought me back to my c ...

Create a Bootstrap Modal that is positioned relative to a specific column

My design consists of 3 columns, and I need to insert a modal into the second column. The challenge is ensuring that the modal stays within the confines of the 2nd column when the screen size changes, specifically for desktop sizes ranging from 1922x1080 t ...

Is it permissible to enclose useEffect hooks within an IIFE?

Currently, I am dealing with a project that is rife with anti-patterns. One issue that has caught my attention is the use of Immediately Invoked Function Expressions (IIFE) around multiple useEffect hooks. Here is a snippet of the code in question: conditi ...

Looking for assistance with changing the class of a span when a radio button is selected

I'm facing an issue with toggling the class of a <span> when a radio button is clicked. <html> <head></head> <style type="text/css"> .eHide { display:none; } </style> <script type="text/javas ...

Tips for utilizing the GROUP BY Clause in Sequelize along with associations

How can I properly utilize the GROUP BY clause in Sequelize to combine data from two tables? This is the SQL query I am attempting to translate into Sequelize: SELECT products.product_name, SUM(order_list.quantity) FROM products JOIN order_list ON prod ...

Synchronize custom directive controller data with data from a factory

As a newcomer to angularjs, I stumbled upon this example that I found somewhere and it works perfectly well. However, I am puzzled by how the data within the customized directive controller remains synchronized with the factory data. Here is the snippet of ...

How can we apply a hover effect to combine two rows in a table as one using CSS?

I'm having trouble figuring out how to highlight every two rows in a table as one when hovering over the current row. For example, if I hover on row 2, rows 2 and 3 should be highlighted. Then when I move to row 4, rows 4 and 5 should be highlighted, ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...