Having difficulty altering the div color in real-time using VueJS

I'm currently in the process of building an application with Bootstrap and VueJS.

My goal is to create a folder structure similar to Google Drive, where I want to make a div stand out in blue once it's selected.

Below is the code snippet:

export default{
  mounted(){  
    $(document).ready(function () {

      let that = this;
      $("#div").on("click", ".folderRectangle", function () {
          $(that).css("background-color", "blue");
          $(".folderRectangle").not(that).css("background-color", "white");
      }); 
    });
  }
}
.folderRectangle { 
  x: 220px; 
  y: 473px; 
  width: 299px; 
  height: 62px; 
  background-color: #FFFFFF; 
  border: 1px solid #BDBDBD; 
  border-radius: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="row">

  <div class="col-xl-3 col-md-6">
    <stats-card>
      <div slot="header" class="folderRectangle" id="div">
        <div class="row">
          <div class="col-3">
            <div class="clearfix">

              <i class="material-icons" id="folder-image">&#xe2c9;</i>

            </div>
          </div>
          <div class="col-9">
            <div class="clearfix" style="position: relative">
              <div>
                <p style="text-align: left">Folder Name</p>
              </div>
              <div>
                <p style="text-align:left">20 files</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </stats-card>
  </div>
  
  <div class="col-xl-3 col-md-6">
    <stats-card>
      <div slot="header" class="folderRectangle" id="div">
        <div class="row">
          <div class="col-3">
            <div class="clearfix">
              <i class="material-icons" id="folder-image">&#xe2c9;</i>
            </div>
          </div>
          <div class="col-9">
            <div class="clearfix" style="position: relative">
              <div>
                <p style="text-align: left">Folder Name</p>
              </div>
              <div>
                <p style="text-align:left">20 files</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </stats-card>
  </div>
  
 </div>

Despite attempting to change the CSS color of the div through onClick, I am encountering difficulties. Can someone offer guidance on what may be causing this issue?

Answer №1

Your approach doesn't align well with the Vue framework. It's generally not recommended to mix jQuery and Vue, although this preference may vary from person to person.

The Vue way of handling this situation would involve having your component trigger an event when clicked, allowing the parent to signal other 'stats-card' components to change color accordingly.

You can utilize references (refs) to keep track of each card. Consider the following example...

Vue.component('StatsCard', {
  props: { isActive: Boolean },
  template: `<div :class="{active: isActive}" @click="handleClick">
  <slot></slot>
  </div>`,
  methods: {
    handleClick () {
      this.$emit('click', this)
    }
  }
})

new Vue({
  el: '#app',
  data: {
    activeCard: null
  },
  methods: {
    setActiveCard(card) {
      this.activeCard = card
    }
  }
})
.folderRectangle { 
  width: 299px; 
  height: 62px; 
  background-color: #FFFFFF; 
  border: 1px solid #BDBDBD; 
  background-color: white;
}

.active .folderRectangle {
  background-color: blue;
}
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <stats-card @click="setActiveCard" ref="card1"
              :is-active="activeCard === $refs.card1">
    <div class="folderRectangle">Content #1</div>
  </stats-card>
  <stats-card @click="setActiveCard" ref="card2"
              :is-active="activeCard === $refs.card2">
    <div class="folderRectangle">Content #2</div>
  </stats-card>
</div>

Answer №2

In this instance, I am showcasing a simple demonstration using Class binding. When you click on an element, it will be highlighted in blue:

new Vue({
  el: "#app",

  data() {
    return {
      selected: -1,

      folders: [{
          name: "Folder 1",
          numFiles: 25
        },
        {
          name: "Folder 2",
          numFiles: 20
        },
        {
          name: "Folder 3",
          numFiles: 21
        }, {
          name: "Folder 4",
          numFiles: 20
        }
      ]
    }
  },
  methods: {}
})
.folderRectangle {
  width: 299px;
  height: 62px;
  background-color: #FFFFFF;
  border: 1px solid #BDBDBD;
  border-radius: 0px;
}

.folder-selected {
  background: #4545ff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />

<div id="app" class="row">

  <div slot="header" class="folderRectangle" v-for="(folder,index) in folders" @click="selected=index" :class="{'folder-selected':selected==index}">
    <div class="row">
      <div class="col-3">
        <div class="clearfix">
          <i class="material-icons" id="folder-image">&#xe2c9;</i>
        </div>
      </div>
      <div class="col-9">
        <div class="clearfix" style="position: relative">
          <div>
            <p style="text-align: left">{{folder.name}}</p>
          </div>
          <div>
            <p style="text-align:left">{{folder.numFiles}} files</p>
          </div>
        </div>
      </div>
    </div>
  </div>

</div>

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

Tips for extracting a substring from a Django variable [HTML]

I am struggling to properly format an img element with a src attribute. The URL example I am working with is , where the number 45 represents the first two characters of the full item.image attribute. My trouble lies in extracting the {{item.image[0,2]}} ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

Using the sortable feature, you can easily rearrange items by simply dragging

I have three selections and I want to remove items between these selection boxes. Instead of using ul tags, I opted for selections because the option values are needed to save the record. I tried using the Sortable feature and modified it based on this exa ...

How can Django implement dynamic CSS for a single item that changes its background dynamically?

I am looking to create a single CSS style that can dynamically change its background based on a Django variable. This becomes more challenging when dealing with a:hover. The initial static style.css code appears as follows: .titles-button h2 a { marg ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

What improvements can be made to optimize this SQL query and eliminate the need for an additional AND statement at the end

I am working on dynamically constructing a SQL query, such as: "SELECT * FROM TABLE WHERE A = B AND C = D AND E = F" Is there a more efficient way to construct this SQL query without adding an extra AND at the end? Here is my current code snippet: le ...

Dealing with Issues in Projectile Image Display: Solutions for Resolving the Error

I've been attempting to change my projectile from circles to images, but I'm encountering this error File "C:\Users\Habib\Desktop\PYTHONGGAME\py.py", line 353, in <module> bullets.append(projectile(round(player ...

Python web application encountering issues running in browser

After successfully creating a Python desktop application with Tkinter library, we decided to convert it into a web app using pyjamas. The conversion process generated html files and javascripts as expected. However, when attempting to open the html file i ...

Issues with table formatting and malfunctioning functions

I created a basic tic-tac-toe game, but I'm having an issue with the table display. It appears squished when the game loads. Is there a way to prevent this and keep the table empty? Additionally, I am using NotePad++ and encountering problems running ...

Sign in and view SESSION data on the current page without any need to refresh the

My website currently features a login form at the top of each page for users to input their username and password. Once the submit button is clicked, I utilize jQuery AJAX method to send the data to login.php without refreshing the page. Here, the credenti ...

Troubleshooting Problems with CSS Before Selector and Margins

Currently, I am attempting to utilize the before selector in order to replicate some list item behavior for elements. Due to constraints where I cannot use list items, it is crucial that I find a way to make styles work effectively. If you would like to s ...

Safari has a unique feature where margins are not factored into the scroll width calculation

I am facing an issue with a container that scrolls horizontally. Inside this container, there are multiple items and I have added a margin to the last item on the right. However, in all browsers except for Safari, the margin is included in the scroll width ...

How to create a stunning Bootstrap Jumbotron with a blurred background that doesn't affect the

I need help making my Jumbotron image blurry without affecting the text inside it! Below is the code from my index.html and style.css files. Any assistance would be greatly appreciated. body { background-image: url(bg1.png); background-repeat: repea ...

Currently working on integrating a countdown timer using the Document Object Model (DOM)

Is it possible to create a timer in the DOM without using any JavaScript? I currently have a JavaScript code for the timer, but I want to convert it to work directly with the DOM without needing to enable JS. Any assistance would be greatly appreciated! ...

Node.js retrieves values through the app.get and app.post methods

In my project, I'm utilizing the app.get and app.post functions in Express on Node.js. Below is an example of how I have used the app.post function: app.post('/status', function(req, res) { if (~packages.STATUSES.indexOf(req.body['s ...

Loading external scripts prior to component loading in Vue.js

Within my Vue project, I have the need to fetch a script from a server location (e.g. https://myurl.com/API.js). This script contains a variable that I intend to utilize within my Vue component/view. The issue arises when I attempt to load this script usi ...

Designing a table with specific limitations on the width of each column

Having an issue with an HTML table that has 3 columns and specific restrictions: Column 1: fixed width, no text wrapping (small text) Column 2: allows text wrapping Column 3: contains descriptive long text with wrapping enabled A row should span the enti ...

Retrieving environmental information within a Vue component

I am trying to display information from my .env file, specifically the APP_NAME, in my components. For example, I want to greet users with Welcome to {{APP_NAME}}. UPDATE After referring to this documentation, I have updated my env file as follows: MIX ...

Preventing select from opening when closing chip in Vuetify: A simple guide

Looking at this specific situation on vuetify.com https://codepen.io/anon/pen/RqoxXY?&editors=101 Regarding the autocomplete feature with chips, is there a way to prevent the select menu from opening when I cancel a chip? I attempted using @click.st ...

Load texture programmatically instead of using MTL files

I've successfully loaded an OBJ file and linked it with an MTL to provide a texture. However, I'm struggling to specify which texture should be associated with the model directly in the code; it seems that the texture only appears on the model if ...