Using Vue.js to alter the CSS class property

I am exploring Vue.js and looking to modify a CSS class property. Here is the HTML code utilizing the specified class:

<div class="customTimer"></div>

Here is the corresponding CSS code:

.customTimer {
        width: 100%;
        height: 10px;
 }

My goal is to alter the width class property using a computed property within the Vue component.

What would be the correct approach to achieve this?

Answer №1

To apply the style, you need to utilize the v-bind:style directive.

var example = new Vue({
  el: '#example',
  data: {
     width:'200px'
  },
  computed: {
    dynamicWidth: function () {
      return this.width;
    }
  },
  methods: {
    adjustWidth: function (event) {
      this.width='100px';
    }
  }
})
#myDiv{
  background-color:red;
  height:200px;
}
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c38393d2935332e">[email protected]</a>/dist/vue.js"></script>

<div id="example">
  <div id="myDiv" v-bind:style="{ width: dynamicWidth }"></div>
  <button v-on:click="adjustWidth()">Adjust Width</button>
</div>

Answer №2

To adjust a characteristic within a category, you have the option to utilize CSS custom attributes:

.fillTimerBar {
    --width: 100%;
    width: var(--width);
    height: 8px;
}

When using Vue, you can link CSS variables to the design:

<div class="fillTimerBar" :style="`--width: ${computedWidth}`"></div>

Answer №3

If you're looking to update the styling of your div using vanilla JavaScript, you can easily do so by adding a new class and combining it with your existing class. Here's an example where the width is set to half:

.fillTimerBar {
        width: 100%;
        height: 8px;
 }
.fillTimerBar .HalfWidth {
        width: 50%;
 }

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

Obtain the CSRF token from a webpage using JavaScript

I am currently working on a project where I need to retrieve the csrf token from a web page built with Django using javascript. The structure of my HTML template is as follows: <div class = "debugging"> <p id = "csrf">{% csrf_token %}</p ...

Navigating the art of employing different fonts for a website

I am looking to incorporate the trainway font into my website, but I'm concerned that the user may not have it installed on their device. Is there a way to showcase text in a specific font without requiring the user to download and install it? Thank ...

Does the message "The reference 'gridOptions' denotes a private component member in Angular" signify that I may not be adhering to recommended coding standards?

Utilizing ag-grid as a framework for grid development is my current approach. I have gone through a straightforward tutorial and here is the code I have so far: typography.component.html https://i.stack.imgur.com/XKjfY.png typography.component.ts i ...

Create two grid components for Material-UI and use Flexbox to ensure that both items have equal height

I'm currently working on ensuring that two grid items have the same height using flex in Material UI, but I've hit a roadblock. It seems like my approach with the Grid element might be incorrect. I've experimented with adjusting the height a ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

Bringing back a Mongoose Aggregate Method to be Utilized in Angular

I'm having trouble returning an aggregate function to Angular and encountering errors along the way. I would really appreciate some assistance with identifying the mistake I am making. The specific error message I receive is Cannot read property &apos ...

The functionality of Ng-Show is acting up

$scope.stay = function() { alert("Inside Keep me In") $scope.timed = false; $scope.isLogStatus = true; } $scope.displayAlert = function() { $scope.timed = true; alert("inside display") } function idleTimer() { var t; $window.o ...

401 Access Denied - Browser extension utilizing Angular JS

In my attempt to implement login functionality within a Chrome extension using Angular, I am consistently encountering a 401 UNAUTHORIZED error. Below is the code snippet I am using: angular.module('chrome-extension') .controller('LoginCont ...

I keep encountering an attach() error every time I try to close a modal that contains a vee-validated form

Every time I try to close a bootstrap modal (using bootstrap-vue) that includes a vee-validated "update" form with vue.js, I encounter the following error: main.js:477686 Uncaught (in promise) Error: [vee-validate] Validating a non-existent field: "#35". ...

Distinguishing between native and custom error objects: a comprehensive guide

When working with errors in my node app, I find it challenging to handle both custom and native errors seamlessly. Errors are not just ordinary JavaScript objects, which adds complexity to error handling. To manage custom errors, I am experimenting with t ...

`Next application will have all accordions simultaneously opening`

Is there a way to make the accordion open only one item at a time? Currently, when I click on one accordion item, all of them expand simultaneously. The data is being fetched from a local JavaScript file and consists of a list of objects with questions a ...

Angular2's hidden feature isn't functioning properly

There is a common suggestion to use *ngIf better than [hidden] but in my scenario, I want to keep the element in the DOM without it being visible. In my component.html file, I have: <article #articleId id="bodyArticle" [hidden]="isClicked"></art ...

Add more functionality to the server.js script

I have the server.js file, which serves as the entry point for my Node application and is responsible for invoking three different functions (these functions are only called once when the server is up, such as creating child processes, validation, etc), wh ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...

Spacious width that doesn't require a horizontal scrollbar for navigation

My dilemma is with the width of my body and background image. I set the body width to 1920px to match the background-image for the header. However, since I have a narrower wrapper inside the body, the header background's width gets cut off by the wrap ...

Ensuring Unique CSS for Diverse Devices: A User-Agent Driven Approach

I am facing multiple challenges and working towards finding solutions. I have developed a webpage and now I want to redirect the link to the CSS file based on the user agent. `<script type="text/css" src="style.css"> </script>` However, inst ...

Tips for defining the width of columns that adapt to different screen sizes in Bootstrap version 4

Utilizing Bootstrap 3, I can effortlessly create a responsive table with adjustable columns using the grid system. Additionally, I have the ability to hide certain columns on smaller devices. For instance, consider this example where the table consists of ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

Vue Formulate unit test fails to detect errors in form validation

Just starting with unit testing Vue components using Jest and Vue-Test-Utils. Playing around with Vue Formulate to handle form fields, everything seems fine when running in the browser. However, encountering an issue during testing where a specific text as ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...