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

What is the best way to send $(this) to a function?

Here is my code snippet: $(document).ready(function(){ var hCount = 0, eCount = 0, nCount = 0, mCount = 0; $("#head").click(function() { var pPos = calculatePosition(hCount); $(this).animate({left:pPos+"px"}, ...

Would you prefer to generate fresh HTML using JavaScript or dynamically load an existing HTML layout using AJAX?

I have a project where I need to generate a large amount of HTML that isn't currently on the page. Up until now, I've been using jQuery to construct the page piece by piece with JavaScript, adding divs and adjusting layouts as needed. Lately, I ...

Calling a C# Webmethod using jQuery AJAX is not working as expected

I'm currently facing an issue calling a web method that I created. The problem lies in the fact that the ajax call isn't reaching my web method, which is puzzling to me because I have another web method in the same file with the same return type ...

What are some effective methods to completely restrict cursor movement within a contenteditable div, regardless of any text insertion through JavaScript?

Recently, I encountered the following code snippet: document.getElementById("myDiv").addEventListener("keydown", function (e){ if (e.keyCode == 8) { this.innerHTML += "&#10240;".repeat(4); e.preventDefault(); } //moves cursor } ...

What is the best way to recycle a variable in TypeScript?

I am trying to utilize my variable children for various scenarios: var children = []; if (folderPath == '/') { var children = rootFolder; } else { var children = folder.childs; } However, I keep receiving the following error message ...

Leveraging the power of Bootstrap and JavaScript to implement a custom Toast feature

I am utilizing Bootstrap 4 to design Toasts, and I am presently developing a JavaScript function to generate a toast. My attempt to create elements within the JS file did not properly style it. index.html <!doctype html> <html lang="en"> ...

Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but noth ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

The font size of the textarea dynamically adjusts based on the size of the screen

Some strange behavior is occurring in the Android default browser when I set the width and height of a textarea to 100%. The font size of the textarea seems to increase based on the screen size, and even though I attempted to alert the font-size using jQue ...

Store the Ajax response in localStorage and convert it into an object for easy retrieval and manipulation

I'm currently working on an Ajax request that retrieves JSON data from the server and then stores it in localStorage for use in my application. However, I feel like my current code may not be the most efficient way to accomplish this task, as I have t ...

The second node child process encounters execution issues in Linux

For a challenge, I needed to find a way to automatically restart my bot within itself. After some trial and error, I came up with a solution. However, when testing on a Raspberry Pi via ssh, the process exits after the first child process ends. Surprisingl ...

Position the read more buttons in JavaScript at the bottom of the div

I designed three boxes in this section with content inside. To enhance the functionality, I added a feature that made the boxes smaller. Everything was functioning perfectly, but I encountered an issue with the alignment of the buttons at the bottom. Is th ...

Allowing the contenteditable attribute to function only on a single line of

My app allows users to create different lists, with the ability to edit the name. However, I am facing an issue where if a user types a new name, it should remain on only one line. I tried adding max height and overflow hidden properties, but it only hides ...

Guide: Generating a DIV Element with DOM Instead of Using jQuery

Generate dynamic and user-defined positioning requires input parameters: offsetHeight, offsetLeft, offsetParent, offsetTop, offsetWidth ...

Creating a delay in a test to ensure a 5-second wait before validating the appearance of an element using React testing library

I am currently facing an issue in my React component where an element is supposed to appear after a delay of 5 seconds. I have been trying to write a test using 'jest fake timers' to check if the element appears after the specified time, but hav ...

"The Django querydict receives extra empty brackets '[]' when using jQuery ajax post to append items to a list in the app

Currently, I am tackling a project in Django where I am utilizing Jquery's ajax method to send a post request. The csrftoken is obtained from the browser's cookie using JavaScript. $.ajax({ type : 'POST', beforeSend: funct ...

Maintaining hover effects even when elements are not in view

I am facing an issue with my absolutely positioned <div> (which serves as a menu) located in the corner of a webpage. The problem arises when I try to animate it on hover, but as soon as the cursor moves beyond the viewport, the hover action stops. I ...

Activating a tab using a JS call in Bootstrap with the data-toggle attribute

My JSP page is using bootstrap's data-toggle="tab" functionality to display tabs. When the page loads, one tab is made active by default. <ul class="nav st-nav-tabs"> <li class="active"><a href="#tab1" data-toggle="tab">First Ta ...

What is an alternative approach to passing arguments to an event handler in a React render component without using a lambda function?

In my React app, I've learned that using lambda functions in the property of a render component can harm application performance. For example: <ConfirmSmsModal modal={args.modal} smsCheck={async (code: string) => { return await this._vm ...

The React Functional Component undergoes exponential re-renders when there is a change in the array

I'm encountering a problem with one of my functional components. Essentially, it maintains an array of messages in the state; when a new message is received from the server, the state should update by adding that new message to the array. The issue ar ...