Using Vue to toggle an active HTML class on click: A tutorial

Can someone assist me with this code snippet that is intended to toggle a class using a Vue on-click event? I'm encountering issues as it's not working and I'm seeing several errors in the console. Any help would be appreciated.

<div id="app5">
    <h1>Dynamic CSS</h1>
    <h2>Example 1</h2>

    <div
            v-bind:class="{available: value}"
            v-on:click="available = !available">
        <span>Click</span>

    </div>
</div>
 

var app5=new Vue({
    el:'#app5',
    data:{
        value: true,
        nearby:false
    }
});

sylesheet

  span{
        background:red;
        color: #fff;
    }

    .available span{
        background: green;
    }

My expectation is for the span background to be initially green and then change to red after being clicked.

Answer №1

Within your click event function, you're attempting to toggle the variable named available, which happens to be the name of your CSS class. To correctly bind classes, you should use the syntax

v-bind:"{classtotoggle: variable}"
.

Therefore, your code should look like this:

<div v-bind:class="{available: value}" v-on:click="value = !value">
  <span>Click</span>
</div>

As a helpful hint, it's advisable to always use a function to manage events with the v-on directive as it allows for easier addition of functionalities in the future.

Hope this guidance proves to be beneficial,

Answer №2

To change the value when clicked, use v-on:click="value = !value" as shown in the code snippet below.

var app5 = new Vue({
    el:'#app5',
    data:{
        value: true,
        nearby:false
    }
});
span{
        background:red;
        color: #fff;
    }

    .available span{
        background: green;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app5">
    <h1>Dynamic CSS</h1>
    <h2>Example 1</h2>

    <div
            v-bind:class="{available: value}"
            v-on:click="value = !value">
        <span>Click</span>

    </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

I am experiencing difficulties with getting Google Analytics to function properly within my VuePress project

Recently, I started a new vuepress project I am attempting to implement Google Analytics to track its progress. However, there seems to be an issue connecting my project with Google Analytics I followed the Documentation Guide ( ) to include yarn add - ...

How can you navigate to different pages in Chrome by selecting radio buttons that are designed as clickable

Currently, I am in the process of developing a website for my job and I have come across a dilemma with two radio button options. To make the text and radio buttons function as links that redirect users to specific pages within the website, I utilized < ...

Vue js external data model

As a beginner starting out with Vue, I have familiarized myself with the basics of imports and exports in ES6. However, I am seeking guidance on the most efficient way to manage data for several components in my project. I want to keep a centralized source ...

In Vue js, a continuous function is executed to check the user's current online or offline status

Hey everyone, I'm looking for a method to determine the online/offline status of users on my web application and constantly monitor it. If a user goes offline, I want to wait 10 seconds to see if they come back online. If not, I need to trigger a spec ...

Troubleshooting Vue Router Loading Problem

After setting up the Vue router in my project, I encountered an issue where clicking on a button would change the URL parameter but the page wouldn't update. Additionally, when directly accessing the URL, the intended page wouldn't load. The src ...

The positioning attribute and flexible height in CSS are essential for creating dynamic

My goal is to create a layout with 3 DIVs inside a container, similar to table rows. top {height = 100px} / middle {height = dynamic} / bottom {height = 100px} I am trying to figure out the best approach to make the height of the middle div dynamic whi ...

Tips for retrieving console data in VueJS Data

Is there a way to review data from a form component in the console without vue taking any action? I need to receive external data and fill in the fields accordingly. I attempted to set a value using document.getElementsByName("nfe.codigo")[0].value = "000 ...

Guide to activating a watcher once the page finishes loading

One of my challenges involves a watcher calling a method: watch: { 'list.items' (n, o) { this.doSomething() } } Every time the page loads, new values are added to list.items like this: methods: { fetchLists(){ axios.get('/ ...

Table borders not displaying properly in Chrome when cells are hidden

I'm dealing with a peculiar issue regarding the display of borders in Chrome when individual cells are hidden within an HTML table. The borders disappear, despite being defined for the row and table elements. Does anyone have experience with this spec ...

Managing key presses with functions in VueJs

Within my component, I am utilizing VueStrap's modal in the following manner: <template> <modal-window v-model="show" v-on:keyup="keyHandler($event)" @ok="submit()" @cancel="cancel()" @closed=" ...

Formatting text over an image

The challenge I am facing involves having an image and text on it in two separate divs with a background color. The length of the text in one div is long while the text in the second div is short, but I want to ensure that the width of both divs are equal. ...

Issues with padding and margin on iOS devices

On my iPhone (iPhone 6, iOS 8), I noticed that the loader is positioned slightly above the button. However, when I use the Chrome mobile emulator, I can't see this issue. I'm puzzled about how to resolve it. What do you think could be causing thi ...

Can you provide guidance on aligning text in a text area to the center?

I've been trying to align my "field labels" in the center of their respective text fields without much success so far. To achieve this, I resorted to using tables but that didn't quite do the trick. Currently, I'm experimenting with CSS prop ...

Center element horizontally at a specified breakpoint and below

Can I use Bootstrap 4 utilities to horizontally center an element like a <select> within a col at a specific breakpoint and below? I want to achieve this without using custom CSS. For instance, I want to center a <select> at xs and sm breakpoi ...

Issue with scrolling to the bottom of collapsed sections in Bootstrap

I have a bootstrap collapse panel and I've added a toggle link at the bottom to allow users to expand and collapse the content with a click. The Issue My problem arises when the menu expands, causing it to scroll all the way to the bottom of the pag ...

Alignment Woes in Bootstrap Designs

I'm seeking assistance regarding the alignment of content on my webpage. The content is not aligning properly with the sidebar and footer, and I'm unsure how to proceed. The page should have a left margin to avoid touching the sidebar, and the fo ...

What could be causing my line-clamp to malfunction when using a fixed height in the Safari browser?

I have a problem with the design of my episode list on mobile devices. The list has a fixed height, and I am using the line-clamp-2 property for the episode titles that exceed two lines. While everything looks fine on my PC and even when using Dev Tools t ...

Collect data from website submissions via email

Is it possible to receive the results via email when someone submits their details on my site using a script? My server does not allow .php or .asp files, only .css. How can I achieve this? ...

Customize the yellow background color of Safari's autofill feature by following these simple

When I open this image in Safari, this is what I see: https://i.stack.imgur.com/KbyGP.png However, this is the code I have: https://i.stack.imgur.com/4wEf0.png References: How to Remove WebKit's Banana-Yellow Autofill Background Remove forced ye ...

I'm having trouble with my tablet view taking priority over my desktop view - what could be causing this issue?

Styling for different screen sizes: @media (min-width: 991px) and (max-width:768px){} .container, .container1, .container2 .container3{ float: left; } .container1{ width: 50%; } .container2{ width: 50%; } .container3{ width: 100%; } /**** ...