Issue with binding classes dynamically in vue with svg elements

I'm attempting to create a custom typing program for one of my students using SVG to display the words and class binding with Vue.js. The goal is to change the color of the characters when the correct key is pressed by the user. However, I've encountered an issue as it's not working as expected. Can anyone help me identify where I made a mistake?

Interestingly, when I manually make changes to the array with a button click, it functions properly. Additionally, when I log the array after a key press event, the array is updated; yet, the character color remains unchanged!

export default {

    data(){
        return{
            word:["a","p","p","e","l","m","o","e","s"],
            letterId:0,
            kleur:[false,false,false,false,false,false,false,false,false],
         }
    },
    methods:{
        checkLetter(event){
            console.log('key pressed: ' + event.which)
            console.log('letter' +this.letterId+' is: ' + this.letter)
            
            if(event.key == this.letter){
                console.log("correct key was pressed")
                this.kleur[this.letterId] = true
                this.letterId++
            }
        }
    },
    computed:{
        
        letter(){
            //determine which letter is expected
            return this.word[this.letterId]
        },
        viewbox(){
            //adjust viewbox according to the length of the word
            var width = (this.word.length * 50) + 50
            return "0 0 "+width + " 70"
        }

    },
    created: function () {
            window.addEventListener('keyup', this.checkLetter)
    },


}
.green{
    font: bold 35px Courier;
    fill:green;
}
.normaal{
   font: bold 35px Courier;
    fill:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div> 
    <svg :viewBox="viewbox" width="100%">
        <text v-for="letter,index in word" :x="index*40" y="45"  :id="index" :class="{green:kleur[index], normaal:!kleur[index]}">{{letter}}</text>
     </svg>   
    </div>
</template>

Answer â„–1

Wow, everything has been completely transformed.

Please incorporate this into your methods and remove it from the computed section.

//locate the letter within the array and return it 
letter(letter){
              return this.word.find(element => {
                  return element == letter;
              })
        },

Next, I updated checkLetter as follows:

checkLetter(event){
            console.log('eventkey: ' + this.letter(event.key));
            //if it finds it then the correct key wes pressed. 
            if(event.key == this.letter(event.key)){
                console.log("correct key was pressed")
                this.kleur[this.letterId] = true
                this.letterId++
            }
        }

Answer â„–2

I have successfully discovered a resolution, however the reason behind its functionality eludes me. I simply introduced a variable named 'test' to my dataset. Additionally, within the checkletter method, I included a line that assigns the test variable to the stringified array as shown below:

checkLetter(event){
            console.log('key pressed: ' + event.which)
            console.log('letter' +this.letterId+' is: ' + this.letter)

            if(event.key == this.letter){
                console.log("correct key was pressed")
                this.kleur[this.letterId] = true
                //modification
                this.test = this.kleur.toString()
                this.letterId++

            }
        }

In the HTML template, I have also implemented a concealed div where the value of test is displayed.

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

What is the best way to configure dependencies for a production deployment when utilizing Babel within the build script?

From what I understand, Babel is typically used for compiling code, which is why it usually resides in devDependencies. However, if I incorporate the Babel command into my build script and want to run npm install --only=prod before running npm run build d ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

What is the reason behind genNewColor function's malfunction?

I'm having trouble with this code that is supposed to generate a random color. The CSS formatting works perfectly, but I suspect there might be an issue with the function itself. When I try to run the code, it doesn't produce any error messages â ...

Would it be frowned upon in JavaScript to use "if (somestring in {'oneoption':false, 'secondoption':false})"?

Is the use of this construct considered a bad practice in JavaScript and could it lead to unexpected behavior? if (e.target.name in {name: '', number: ''}) { // do something } This code checks if the 'name' attribute of an ...

What is the process for including a JavaScript file in an HTML document?

Greetings to all and thank you for taking the time! I have a straightforward query for you.. I have designed an html page featuring only a basemap (open street map). Moreover, I possess a javascript file which utilizes your coordinates to calculate a perce ...

Managing the Response from Google Geocode API in a Vue JS Component

I am facing an interesting challenge. I have a scenario where users can choose between two options - using their current location or entering a zip code. When a user inputs a zip code, I need to make a call to the Google geocode API to retrieve the central ...

Switching the navbar image with HTML and JavaScript when clicked

Looking to change the image upon clicking on any of the navbar items. Emulating the navigation bar behavior from this website : This is my current progress : The HTML file : <html lang="en"> <head> <meta charset="utf-8" /> ...

Python Scrapy: Extracting live data from dynamic websites

I am attempting to extract data from . The tasks I want to accomplish are as follows: - Choose "Dentist" from the dropdown menu at the top of the page - Click on the search button - Observe that the information at the bottom of the page changes dynamica ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...

Separate a string using commas but disregard any commas inside quotation marks

Similar Question: JavaScript code for parsing CSV data There is a string that looks like this: "display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a> ...

Tips for adding extra spacing between icon and text field using Vuetify

The code snippet below is used for the username section: <v-text-field prepend-icon="fas fa-user" height="60px" placeholder="Username" outlined ></v-text-field> Is there a way to add space between the user ...

Categorize a collection of objects based on shared characteristics

I am in need of the count for the current week only. Specifically, I want to calculate monthly totals with a breakdown per week. Currently, I can retrieve the weekly count for each month. Now, my goal is to display only the existing weeks. For example, if ...

Get the application/pdf document that was just sent to you from the software backend

I am facing an issue with downloading a PDF file sent from the backend. Upon receiving a blob response, I notice that when I download and view the file, the sheets are empty, matching the expected number of sheets. Could this be a coding problem? Current ...

"Sparkling div animation with the use of jQuery's .hover() function

<script> $(document).ready(function () { $("#logo_").hide(); $("#logo_learn").hide(); }) function sl() { $("#logo_learn").slideToggle(500); $("#logo_").fadeIn(); } function hl() { $("#logo_learn").slideToggle(500); $("#logo_ ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...

Utilizing NGRX reducers with a common state object

Looking for a solution with two reducers: export function reducer1(state: State = initialState,: Actions1.Actions1); export function reducer2(state: State = initialState,: Actions2.Actions1); What I want is for both reducers to affect the same state objec ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

Troubleshooting Nuxtjs configuration issue with setting up Github Pages

Trying to set up Github Pages deployment for NuxtJS but facing issues with the configuration file. I followed the documentation, but still can't get it right. The documentation suggests adding this code snippet in the file, which I tried multiple tim ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...