Using Vue.js to detect changes in a value and dynamically highlight the text

I am working on a simple script that generates random numbers every few moments. I want to change the background color whenever the random number is not equal to the one before it. Is this possible? For example, if the random numbers generated are 1, 1, and then 3, I would like to highlight the background when it reaches 3. Thank you for your help!

Link to code

new Vue({
  el: '#app',
  data: {
    rand: 0
  },
  mounted : function(){
   var me = this;
    setInterval(function(){
        me.rand = Math.floor(Math.random() * 4) + 1 ;
      me.$forceUpdate();
    },1000)
  }
})


<div id="app">
  <p>{{rand}}</p>
</div>

Answer №1

Create a data property to hold the information about whether the updated value is different from the current one and link the background-color with it:

new Vue({
  el: '#app',
  data() {
    return { 
      randomNumber: 0,
      isDifferent: false
    }
  },
  mounted() {
    setInterval(() => {
      let newRandomNumber = Math.floor(Math.random() * 4) + 1;
      this.isDifferent = newRandomNumber !== this.randomNumber;
      this.randomNumber = newRandomNumber;
    }, 1000);
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.2/vue.min.js"></script>
<div id="app">
  <p :style="{ 'background-color': (isDifferent) ? 'gold' : 'initial' }">{{randomNumber}}</p>
</div>

Answer №2

One effective method is to utilize a watcher along with a class binding. Check out this example on jsfiddle: https://jsfiddle.net/omarjebari/wjf8qbt0/18/

<div id="app">
   <div class="random-element" v-bind:class="{ active: isChanged }">{{ rand }}</div>
</div>
<script>

    new Vue({
        el: "#app",
        data: {
            rand: 0,
            isChanged: false,
        },
        mounted : function(){
            setInterval(() => {
                this.rand = Math.floor(Math.random() * 4) + 1;
            }, 1000);
        },
        watch: {
            rand(newVal, oldVal) {
                console.log(`${newVal} vs ${oldVal}`);
                if (newVal !== oldVal) {
                    this.isChanged = true;
                    setTimeout(() => {
                        this.isChanged = false;
                    }, 300);
                }
            }
        },
    })
</script>
<style>
    div.random-element {
        height: 30px;
        color: black;
        padding: 5px;
    }

    div.active {
        background-color: red;
    }
</style>

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

Strategies for setting up the runtime dynamically for Nextjs API routes

After deploying my Next.js 13 app on Cloudflare Pages, I encountered an issue with the API routes. To address this, I had to export the runtime variable from each route in the following manner. export const runtime = "edge" During local developm ...

Creating custom mesh Morph Target Animations using THREE.js

I'm currently working on creating an animation that showcases the revolution of a 2D function around an axis to produce a 3D surface. Successfully rendering the surface, my next task is to implement the animation section using MorphTargets. Despite m ...

Interactive Chart with Angular for Multiple Selections

I have a single page with a list menu By utilizing the list menu, I am able to generate various types of charts such as line chart, bar chart, pie chart, and more. However, I would like the previously selected charts, like the line chart, pie chart, etc. ...

State calculation occurs too tardily

I'm working on creating a simple like button that changes color based on whether it's liked or not. I've tried to calculate this beforehand using React.useEffect, but it seems to be calculating afterwards instead... The hearts are initially ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

What is the best way to trigger a function when a chart changes in Nuxt using Vue JS?

How can I trigger a function whenever a chart is loaded or changed in Vue Nuxt JS? I've tried using created, mounted, updated, and beforeMount but none of them seem to work. Can anyone offer any guidance? Edit 1: Here's the code snippet: upd ...

Struggling to Parse JSON Responses?

Utilizing AJAX/JQuery to communicate with a WCF service presents its own set of challenges. One common method is implementing .NET try/catch error-handling on the service-side to manage different scenarios, such as user timeout errors. Typically, the servi ...

Efficiently Displaying Multiple HTML Elements in React Native WebView

I am currently working on developing an Epub reader in React Native and facing a challenge. I need to find a way to efficiently transfer multiple html content files from the Epub container to the webview in order to achieve seamless pagination. ...

Enabling and disabling multiple input fields based on the status of a checkbox in order to manage dynamic inputs

I need help with a situation involving dynamic input fields and checkboxes. My goal is to disable the input field if the checkbox with the corresponding ID is checked. Here is the PHP code snippet: <table class="table table-striped"> <thead& ...

An error occurred while trying to add a property to an array because the object is not extensible: TypeError -

In my code, there is an object named curNode with the following structure: { "name": "CAMPAIGN", "attributes": {}, "children": [] } I am attempting to add a new node to the object like this: curNode!.children!.push({ name: newNodeName, ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

Is real-time updating possible with data binding in Polymer and JavaScript?

I have a scenario where I am working with two pages: my-view1 and my-view2. On my-view1, there are two buttons that manipulate data stored in LocalStorage. On my-view2, there are two simple div elements that display the total value and the total value in t ...

Exploring the methods of accessing $scope within an AngularJS directive

My custom directive is designed for handling form controls like input, select, and radio buttons. Each input has a default value set, and if the corresponding value exists in $scope.answers, it should be displayed in the input box. The code snippet below ...

Return to the main page by clicking on the link #id

I am in the process of creating a personalized Wordpress theme that consists of one main page with 8 additional sub-pages. I am wondering how I can navigate to a specific section using an ID (for example, <a href="#how">how</a>) from the sub-pa ...

Utilizing jQuery to access Flash functions

When trying to access functions in my SWF using jQuery code, I encounter a compatibility issue with Internet Explorer. The code works fine in all other browsers except for IE. As jQuery is supposed to provide cross-browser functionality, writing addition ...

The resend email feature isn't functioning properly on the production environment with next js, however, it works seamlessly in the development environment

import { EmailTemplate } from "@/components/email-template"; import { Resend } from "resend"; const resend = new Resend("myApiKey"); // this works only in dev // const resend = new Resend(process.env.NEXT_PUBLIC_RESEND_API_KE ...

Contrasting the use of jQuery versus AJAX for updating static page text

While I haven't fully grasped the concept of AJAX yet, my understanding is that it can be beneficial for updating specific parts of a webpage. Does using AJAX only make sense when you require server interaction? I am looking to replace text on a webp ...

What is the method to utilize global mixin methods within a TypeScript Vue component?

I am currently developing a Vue application using TypeScript. I have created a mixin (which can be found in global.mixin.js) and registered it using Vue.mixin() (as shown in main.ts). Content of global.mixin.js: import { mathHttp, engHttp } from '@/ ...

The optimal and most secure location for storing and retrieving user access credentials

After receiving a list of locations accessible to the session user from the server, I am seeking the ideal location to store these roles in Angular. This will allow me to determine whether or not to display specific routes or buttons for the user. Where ...

mentioning a JSON key that includes a period

How can I reference a specific field from the JSON data in Angular? { "elements": [ { "LCSSEASON.IDA2A2": "351453", "LCSSEASON.BRANCHIDITERATIONINFO": "335697" }, { "LCSSEASON.IDA2A2": "353995", "LCSSEASON.BRANCHIDITER ...