Checking the Focus of an Element in Vue.js

Below is the code I am working with:

<template>
  <div id="app">
    <span
      contenteditable="true"
      spellcheck="false"
      style="width: 800px; display: block"
      :v-text="textEl"
      @focus="focused = true"
      @blur="focused = false"
    />
    {{ focused }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      focused: false,
      textEl: null,
    };
  },
  methods: {
    start() {
      if (this.focused) {
        this.textEl = "text with focus";
      } else {
        this.textEl = "text with not focus";
      }
    },
    mounted() {
      this.start();
    },
  },
  components: {},
};
</script>

Access full code here.

Even when the span element is focused, the method start does not execute. Why could this be happening?

I aim to display "text with focus" when the element is in focus and "text with not focus" otherwise. How can I achieve this considering that the start method is not functioning within mounted?

Answer №1

This particular function is only executed upon the initialization of the component.

To ensure that it runs whenever the value of focused changes, you can convert start into a watcher like so:

watch: {
    focused(newVal) {
        if (newVal) {
            this.textEl = "text with focus";
        } else {
            this.textEl = "text with not focus";
        }
    }
}

Alternatively, you can directly call the start function within the event handlers:

@focus="start()"
@blur="start()"
...
start() {
    this.focused = !this.focused;

    if (this.focused) {
        this.textEl = "text with focus";
    } else {
        this.textEl = "text with not focus";
    }
},

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

Is there a way to remove the bold styling from text next to JavaScript?

I recently launched a website at www.mvscaccounting.com, and I added a search engine made from javascript at the bottom of the page. Next to it, I wanted to put a "all rights reserved" notice. However, whenever I try to add any text next to the search engi ...

What could be preventing me from registering the service-worker.js on localhost?

While attempting to develop a VueJs app, I encountered an issue with the service-worker.js file breaking. The build process I used was: npm run build-dev Here are the settings: "build-dev": "vue-cli-service build --mode development", ...

Hiding Certain Words on a Website

Is there a way to hide specific text strings on a website? For instance, suppose I want the string "hxxp://nullrefer.com/?" to be invisible whenever it appears on my page. If a URL like "hxxp://nullrefer.com/?hxxp://www.Amazon.com" is mentioned, I only w ...

The `Ext.create` function yields a constructor rather than an object as

Ext.application({ name: 'example', launch: function() { var panel = Ext.create('Ext.panel.Panel', { id:'myPanel', renderTo: Ext.getBody(), width: 400, ...

Guide on implementing Vuetify Component Slot Function

Can someone help me figure out how to implement the v-alert dismissible component with additional functionality when the close button is clicked? According to the documentation, there is a function called toggle in the close slot that allows you to "Toggle ...

Can the value of ng-model be altered without using ng-change function?

Can the ng-model value be altered without using the ng-change function? The method below does not seem to work. <div ng-app="myApp"> <div ng-controller="MyCtrl"> <input id="checkbox" type="checkbox" ng-model="field"> <div> {{field ...

Can the Automator tool capture a specific section of a website in a screenshot?

Is it possible to use automator to navigate through a store's website category and open each product in a new tab? Alternatively, is there a software that can extract all the product URLs from a specific website? For example, this website has 14 prod ...

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Link a function to a button in a 3rd party library

Whenever I click a button, there is a possibility of an alertify alert window appearing randomly. The alertify alert popup serves as a more aesthetically pleasing alternative to the traditional javascript Alert. Alertify library Below is a snapshot depic ...

Guide on extracting a particular segment of JSON data and converting it to a string

Recently, I started delving into JSON, node.js, and JavaScript. My small node.js server pulls a JSON object (referred to as weatherData below) from openweathermap.org. My goal is to only display a specific part of the JSON object – the "temp" section. Cu ...

Tips for sending a state into the gtm.js function?

As an intern at a startup, I am the sole front-end developer responsible for coding a website in Next.js. My boss has requested that I incorporate Google Tag Manager into the project. Following the example provided by Next on their GitHub page, I have succ ...

The visibility of overflow-y does not seem to be working properly when overflow-x is

https://i.sstatic.net/hihjC.png .iati-list-table { overflow-x: auto; overflow-y: visible; } When I apply overflow-visible, a scroll bar appears. But when I use overflowy-hidden, the tooltip is cropped. How can I set it so that overflow x is auto a ...

Switching to a jQuery IF statement instead of a FOR loop allows for more streamlined

I recently made a request to sqlite and am fetching data using the code snippet below: var rows = results.rows; alert(rows.length); for (var index = 0; index < rows.length; index++) { var x = rows.item(index); $( ...

Having trouble with installing the most recent versions of React App dependencies

After cloning a project from GitHub, I attempted to install dependencies using npm install, but encountered an error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email ...

Ways to establish a default option in a dropdown menu using JavaScript

I am currently attempting to link a JSON object to a dropdown in the following manner: JSON data "securityQuestions": [ "First Pet's Name", "City I was born in", "Mother's Maiden Name", "Favorite teacher's Name" ] This i ...

Obtaining data from a CSV file and transforming it into JSON format results in an array

Currently, I am working on a function that takes a JSON object and prints it out as strings: GetAllArticles: (req, res) => { var allArticles = getAllArticles(); res.setHeader("Content-Type", 'application/json'); res.w ...

"Utilizing the @blur event in the v-autocomplete component of Vuet

I am experiencing an issue with a v-autocomplete component where I need to call a function @blur, but it does not seem to work the same way as with v-select or v-text-field components. Is there something different that I should be doing? <v-autoco ...

Struggling to calculate the total of a property within an array of objects

I'm currently trying to calculate the sum of a specific property within an array object. Although I successfully accomplished this in one component, I am encountering difficulties replicating it in another. The error message being displayed is: this. ...

Disabling a Field in Angular While Preserving its Value

Hey there, late night folks! I have a quick question about Angular. I'm working with a form that includes a specific field where I set the value using patchValue, but I also need to disable this field. The issue is that after disabling it, the value i ...

Sharing data between view and controller in Laravel: a guide

Currently, I am developing a product cart feature that includes subtotal and grand total values displayed within <span> tags. My goal is to pass the grand total value to the controller for further processing. However, I encountered an issue where the ...