What if the v-on:click event is applied to the wrong element?

I'm attempting to manipulate the anchor tag with jQuery by changing its color when clicked, but I'm struggling to correctly target it.

<a v-on:click="action($event)">
    <span>entry 1</span>
    <span>entry 2</span>
</a>

The event.target in action always refers to either the first or second span within the anchor tag, rather than the actual anchor tag itself.

For instance:

$( $event.target ).css( "backgroundColor", "red" )

Whenever I click on the "a" tag, one of the spans will change to red instead of the "a" tag that has the v-on:click directive. Is there a way to specifically target the element with the click directive?

Answer №1

Do not use $event.target, instead, utilize $event.currentTarget. Then proceed to apply your style to the a tag.

new Vue({
  el: "#app",
  methods: {
  action: function($event){
    $($event.currentTarget).css( "backgroundColor", "red" )
    }
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app">
  <a v-on:click="action($event)">
    <span>entry 1</span>
    <span>entry 2</span>
  </a>
</div>

Answer №2

Have you considered using jQuery along with vuejs? Instead, utilizing the full potential of vuejs can lead to a solution like this:

.clicked {
  background-color: red;
}
<a v-on:click="aClicked = true" :class="{ 'clicked': aClicked }">
    <span>entry 1</span>
    <span>entry 2</span>
</a>

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

The loading time for the Ajax request is unreasonably slow

I am currently managing a website dedicated to League of Legends. My main task involves requesting statistics from the Riot Games API based on a player's name, which returns the information in JSON format. However, there is a significant delay in load ...

Knockout Observable Array causing UI to freeze and not refresh properly

I recently started using knockout and am exploring the use of observable arrays to track changes from the UI. The initial data is loaded into the array and I'm attempting to dynamically add new objects to the array from another screen. Although I hav ...

Comparison: JavaScript Cookies vs PHP Cookies

I have been trying to implement the following code: JS: Cookies.set(post_id + '_' + user_ip, post_id + "_" + user_ip, { expires: 1 }); PHP: $cookie_str = $post_id.'_'.get_client_ip(); if (isset($_COOKIE[$cookie_str_]) ){ print_r ...

Guidelines for transforming an HTML string into a JavaScript document

Is there a simplified method to transform an HTML string into JavaScript code that generates the same markup using the DOM? Something similar to: Input <div class="foo" tabindex="4"> bar <button title="baz">bar ...

Enzyme in Action: Using React.js to Emulate a Click Event

I have been working on a React.js application which is a straightforward Cart app. You can take a look at the code sandbox here: https://codesandbox.io/s/znvk4p70xl The issue I'm facing is with unit testing the state of the application using Jest and ...

JavaScript validation code for verifying hostnames with a specified domain name

I need a customized validation check for my order form where users are asked to enter their server hostname. The challenge is that I'm using WHMCS with encrypted PHP code and IonCube loaders, making it difficult to add this check. Users can input any ...

When attempting to showcase an MUI icon that was imported, I encounter the following issues: Invalid hook call and the <ForwardRef(SvgIcon)> component

Encountering issues while trying to display an imported MUI icon leads to the following errors: Error: https://i.stack.imgur.com/USdEx.png Sample Code: import React from 'react' import ThreeDRotation from '@mui/icons-material/ThreeDRotati ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

A step-by-step guide on utilizing NuxtLink to successfully pass data between pages

Having an issue with Nuxt Link: -Initially, I use a v-for to generate some HTML <li v-for="store in stores"> <p>{{store.companyName}}</p> <p> {{store.url}} </p> <NuxtLink :to="nextPage">C ...

Implementing AngularJS table filters on user click

As a newcomer to angularjs, I am attempting to implement a filter on click. The user will select a source and destination, then click on the filter button. The table should display results based on the input. Upon page load, the table should already contai ...

Deploying a static website using Node.JS without relying on any frameworks

I am currently working on deploying static web pages, which include HTML, CSS, and JS files, onto Node.js without utilizing any frameworks such as Express. I started by placing all the necessary webpage files into a public folder and then called the index. ...

The value of Component.name is not consistent during the BUILD process in NextJS

I have multiple pages with different layouts. To switch between layouts, I am currently using the Component.name in _app.js. While this approach works during development, after building and starting the project with npm start, it seems like the Component.n ...

When converting to .glb format, the material becomes invisible unlike in .gltf files

After exporting a model using the glTF exporter in Blender 2.8, I noticed that when exporting to .glb format, the texture is no longer visible. Strangely, when I view the .glb file in the glTF Viewer from it appears fine, but in my environment and in the ...

WebWorker - Error in fetching data from server using Ajax call

I've been experimenting with making AJAX calls to an ajax.htm file using web workers. The goal is to have the data continuously updated at set intervals. Although I'm not seeing any errors and the GET request appears to be successful, the data i ...

Is it possible to dynamically load an npm package based on the user's browser?

My current goal is to utilize the ResizeObserver Polyfill specifically for Edge browsers. I noticed the concept of ponyfill in the npm package documentation. Would I need to develop my own ponyfill, or is there an alternative approach that could be consi ...

Verifying file types with HTML5 drag and drop feature

Is it possible to change the drop zone's background color to green or red based on whether the dragged payload contains supported file types (JPEG)? Do Gecko and Webkit browsers have the ability to determine the file type of drag and drop files? ...

Tips for accessing the URL in PhoneGap and parsing the response with jQuery

Currently, I am working on a task in PhoneGap which involves creating a registration page. When the user clicks on the registration page, the values entered will be sent to a specific URL. If the user is already registered or not, the data will be returned ...

Transferring the AJAX response into a JavaScript variable

New to AJAX and JS here. I am implementing an AJAX code that fetches data from a php service. I am trying to figure out how to store the returned data in a JavaScript variable, which I can then display on the UI. Below is my AJAX code snippet: <script ...

Send information as FormData object

I'm getting the data in this format: pert_submit: {systemId: "53183", pert-id: "176061", score: 0, q2c: "3\0", q2t: "", …} Now I need to send it as FormData in my post request. Since I can't use an ...

How do I rearrange the order of a collection in Firestore using a reference that I already have?

Is there a method to maintain a reference of the same collection while altering the ordering using firestore? TLDR: I am looking to achieve similar functionality as demonstrated in: , but since my data is sourced from firestore, I am struggling to find th ...