Unlocking elements in Vue.js through functions

Looking to dynamically add a class to the label element when focusing on an input element below it. The current HTML and JS code I'm using is as follows:

HTML:

<label for="formProductId" ref="productIdLabel" class="form-element-title">Product ID</label>
<input id="formProductId" @blur="toggleFocus('productIdLabel', false)" @focus="toggleFocus('productIdLabel', true)" v-model="filterValues.productId" :name="filterOptions.productId === true ? 'productId' : false" type="text">

JS:

toggleFocus(ref: string, enable: boolean) {
    if (enable) {
        (this.$refs[ref] as HTMLElement).classList.add("js-focused");
    } else {
        (this.$refs[ref] as HTMLElement).classList.remove("js-focused");
    }
}

Wanting to enhance this functionality by removing the ref attribute and toggling the js-focused class directly from the selected element. Any ideas on how to select the closest label element and modify its class?

Answer №1

A more efficient approach involves utilizing dynamic classes. Take a look at this example:

new Vue({
  el: '#app',
  data: {
    productIdLabel: false
  }
})
.js-focused {
  background-color: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <label for="formProductId" class="form-element-title" :class="{'js-focused': productIdLabel == true}">Product ID</label>
  <input id="formProductId" @blur="productIdLabel = false" @focus="productIdLabel = true" type="text">
</div>

Implement this with components and multiple form inputs:

Vue.component("form-label", {
  template: `<div>
  <label :for="info.id" class="form-element-title" :class="{'js-focused': isFocused == true}">{{info.label}}</label>
   <input :id="info.id" @blur="isFocused = false" @focus="isFocused = true" type="text">
</div>`,
props: ["info"],
data: function(){
return {
isFocused: false
}
}
})
new Vue({
  el: '#app',
  data: {
    form: [{
      label: "Product Id",
      id: "formProductId"
    }, {
      label: "Another Element",
      id: "anoterId"
    }, {
      label: "Third Element",
      id: "thirdId"
    }]
  }
})
.js-focused {
  background-color: lightblue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <form-label v-for='el in form' :info='el'></form-label>
</div>

Answer №2

You can utilize the previousElementSibling property in combination with event.target.

For instance:

new Vue({
  el: '#app',
  methods: {
    toggleLabelColor(event) {
      event.target.previousElementSibling.classList.toggle('input-focused')
    }
  }
})
input {
  display: block;
}

.input-focused {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <label>I turn green when focused.</label>
  <input @focus="toggleLabelColor" @blur="toggleLabelColor">

  <label>I turn green when focused.</label>
  <input @focus="toggleLabelColor" @blur="toggleLabelColor">

  <label>I turn green when focused.</label>
  <input @focus="toggleLabelColor" @blur="toggleLabelColor">
</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

Conceal the scroll bar while the page preloader is active

Is there a way to hide the scroll bar while the preloader is loading on a webpage? I want to prevent users from scrolling until the preloader disappears. I have tried using CSS and setting the body overflow to hidden, but it's not working as expected. ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

creating dynamic column headers with JavaScript

I am looking for a way to make the column names dynamic so that I don't have to manually update them every time. Here is my code snippet: jqGrid11.prototype = { display : function() { $('body').append(this.html.join("")); $("#jqGrid").j ...

Locate the Next Element Based on its Tag Name

CSS <div> <a href=''> Red </a> </div> <div> <div> <a href=''> Blue </a> </div> </div> <a href=''>Green</a> JavaScript $(document).ready(f ...

Using jQuery code within PHP pages is a convenient and powerful way to

I am currently facing an issue with PHP and jQuery. Here is the structure of my website: header.php - contains all css and js files. index.php - main page. sidemenu.php - includes the side menu in index.php Within sidemenu.php, I have the following JS ...

Determine line-height and adjust positions using JavaScript in the Chrome browser

I am creating a basic text reading application with a line to aid in easy reading. The functionality involves using the up and down arrow keys on the keyboard to adjust the position of a red line based on the line-height property. This is accomplished thr ...

Which is better: using multiple makeStyles or just one in Material UI?

Uncertain about the best approach in this situation. Is it acceptable to generate styles using makeStyles for each component individually, or would it be better to create one in the base component and simply pass down class names? ...

Datatables ajax response not loading data into table

I don't have much experience with JavaScript, so I believe there may be a misconfiguration or something that I'm overlooking. My current setup involves using Datatables v1.10.7. I have a table with the required parts - a thead, tfoot, and a tbod ...

button that takes you back to the top of a mobile website

I want to customize the Scroll To Top button so that it only appears once the user begins scrolling down, rather than always being visible even when at the top of the page. Just a heads up, I don't have much experience with JavaScript, so I might need ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

"Is it possible to use a Twitter widget with Mootools

I have been attempting to create a marquee for my twitter Account on my website. After some trial and error, I was able to achieve this using jQuery. Here is the code I used: <div id="twitter"> <p> Loading.....</p> <n ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

Using the feColorMatrix SVG filter in CSS versus applying it in JavaScript yields varied outcomes

If we want to apply an SVG filter on a canvas element, there are different ways to achieve this. According to this resource, we can apply a SVG filter to the CanvasRenderingContext2D in javascript using the following code snippet: ctx.filter = "url(#b ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Quickest method for sorting an array of objects based on the property of another object's array

Within my code, I have two arrays of objects, both containing a "columnId" property. My goal is to rearrange the first array to match the order of the second. I attempted the following method: filtered = visibleColumns.filter(function(v) { re ...

I'm puzzled as to why my recursive function is repeatedly calling itself without meeting the necessary logical condition. Can anyone provide guidance on

As I delve into a basic recursion, I am observing an interesting phenomenon where the logic governing the recursion is activated even when a false parameter is present in the return statement for the ternary rule. This particular recursive function perfor ...

There are no errors in the HTML markup, however, there is an issue where the client-side rendered virtual DOM tree does not align with the

I can't seem to figure out why I keep getting this error message: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, such as nesting block-level elements inside <p>, ...

The CORS middleware seems to be ineffective when used in the context of Node.js

I have set up my REST API on a Raspberry Pi server and connected it to the public using localtunnel. I am trying to access this API from a localhost Node.js application. The Node application is running on Express and includes some static JS files. However, ...

Utilizing JQuery to Modify XML File Content

Looking to retrieve data from an XML file using jQuery and display it in a textbox? If you want changes made in the textbox to reflect back in the original XML file, there are ways to achieve this. Here is some code that can help: <html><head&g ...

Fetching data from local JSON file is being initiated twice

I need some help understanding why my code is downloading two copies of a locally generated JSON file. Here is the code snippet in question: function downloadJson(data, name) { let dataStr = 'data:text/json;charset=utf-8,' + encodeURICompo ...