Press the div, excluding the button - Vue

I have a basic div that spans 100% of the width, containing a button inside.

The issue I'm facing is that when I add a click event to the div, the entire div becomes clickable (including the button within it).

What I want is for the whole div to be clickable with one method, while the button should trigger a different method when clicked.

<div class="full-width" @click="method1">
  <button @click="method2">Click me</button>
</div>
<script>
export default {
methods: {
  method1() {
    console.log("Div clicked")
  },
  method2() {
    console.log("Button clicked")
  }
}
</script>

Answer №1

Vue offers two different methods to achieve this functionality:

  1. You can utilize @click.self on the div element and @click on the button
  2. Alternatively, you can apply @click.stop on the button and @click on the div

The first approach instructs the div to only respond to events where the target is itself. On the other hand, the second method prevents event propagation on the button, ensuring that the click event does not propagate to the div

edit: included both techniques for handling select elements

Feel free to check out the demonstration below:

new Vue({
  el: '#app',
  data: () => ({
    msg1: '',
    msg2: '',
    msg3: '',
    msg4: '',
  }),
  methods: {
    method1(v) {
      this[v] = 'clicked on div';
    },
    method2(v, elm = 'button') {
      this[v] = `clicked on ${elm}`;
    }
  },
});
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="92fcffffdaf8c6ff">[email protected]</a>/dist/vue.js"></script>

<div id="app">
  <div style="border: 2px solid red; width: 100%" @click.self="method1('msg1')">
    <button @click="method2('msg1')">click me</button>
  </div>
  <div>{{ msg1 }}</div>

  <div style="border: 2px solid green; width: 100%; margin-top: 20px" @click="method1('msg2')">
    <button @click.stop="method2('msg2')">click me</button>
  </div>
  <div>{{ msg2 }}</div>

  <div style="border: 2px solid blue; width: 100%; margin-top: 20px" @click.self="method1('msg3')">
    <select @click="method2('msg3', 'select')">
      <option value="">--Please choose an option--</option>
      <option value="dog">Dog</option>
      <option value="cat">Cat</option>
      <option value="hamster">Hamster</option>
      <option value="parrot">Parrot</option>
      <option value="spider">Spider</option>
      <option value="goldfish">Goldfish</option>
    </select>
  </div>
  <div style="text-align: right">{{ msg3 }}</div>

  <div style="border: 2px solid orange; width: 100%; margin-top: 20px" @click="method1('msg4')">
    <select @click.stop="method2('msg4', 'select')">
      <option value="">--Please choose an option--</option>
      <option value="dog">Dog</option>
      <option value="cat">Cat</option>
      <option value="hamster">Hamster</option>
      <option value="parrot">Parrot</option>
      <option value="spider">Spider</option>
      <option value="goldfish">Goldfish</option>
    </select>
  </div>
  <div style="text-align: right">{{ msg4 }}</div>
</div>

Answer №2

Give this a try, it should work like a charm.

<template>
  <div id="myDiv" @click="handleDivClick">
    <button id="myButton" @click="handleButtonClick">Click me</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleDivClick(event) {
      if (event.target.id === 'myButton') {
        // Button click logic
        // Implement your code here
      } else {
        // Div click logic
        // Implement another code here
      }
    },
    handleButtonClick() {
      // Button click logic
      // Implement your code here
    },
  },
};
</script>

If this doesn't solve the issue, I recommend using vanilla JavaScript for this implementation.

Answer №3

To ensure the button does not trigger the div's click event, use @click.stop on the button and bind @click to the div element. Here is an example:

<div class="full-width" @click="handleMethod1">
  <button @click.stop="handleMethod2">Click Me</div>
</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

Encountered an Xpath error while attempting to create a random email generator using Selenium IDE

While attempting to execute a script, I encountered an "element not found" error with Selenium failing to detect the xpath. My goal is to randomly generate email addresses. Every time there is an error message stating: [error] Element .//[@id='GmailA ...

Incorporating External HTML Content Using JQuery Function

Looking for assistance with a JQuery function: function addSomeHTML() { $("#mysection").html("<div id='myid'>some content here</div>"); } I am trying to have this part: <div id='myid ...

Using Angular's async, you can retrieve a value returned by a promise

Within the library I am currently utilizing, there is a method called getToken which can be seen in the following example: getApplicationToken() { window.FirebasePlugin.getToken(function(token) { console.log('Received FCM token: ' + to ...

Asynchronous waterfall call in Node.js to call the method before

Is it possible to invoke a previous method within async.waterfall from a subsequent method? async.waterfall([ function (callback) { }, function (reservationStatus, callback) { }, function (reservationStatusList, f ...

How to simultaneously play a sound and display an alert message using JavaScript

My JavaScript code attempts to play a sound and then display an alert, but the alert always shows up first. When I click 'ok', the sound plays. How can I make it so that the sound plays before the alert appears? <script> function play() { ...

What is the best way to send an object to Vue Component?

How can I properly call a Vue Component with a data object? The todo-item tag works as expected, but the todo-item2 tag does not produce any output. I was expecting the same result. Here is the HTML code: <div id="app"> <todo-item v-bind:te ...

Exploring External Functions in Angular Beyond the Library

Transitioning from standard JavaScript to Angular has been a bit challenging for me, especially when working with the Google Places library (or any other asynchronous callback). Here is the code snippet: var sparkApp = angular.module('sparkApp' ...

A custom class that uses toggleClass() does not trigger an alert upon a click event

I am encountering an issue with the toggleClass() function in jQuery that I haven't seen addressed before. Despite successfully toggling the class of one button when clicked, I am unable to trigger a click event on the newly toggled class. Here is th ...

Using router.get with a redirect in Express

Can you directly invoke a router.get(...) function in Express? Let's say I have a router.get('/my-route', function(req, res) { ... });, is it feasible to then, within another part of my code, use res.redirect('my-route'); with the ...

Putting off the execution of a setTimeout()

I'm encountering difficulties with a piece of asynchronous JavaScript code designed to fetch values from a database using ajax. The objective is to reload a page once a list has been populated. To achieve this, I attempted to embed the following code ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

Stop users from refreshing or closing the window while an axios request is being processed

I'm in the process of creating a dynamic Web Application that involves utilizing Axios.get requests. Given that Axios operates asynchronously, my approach includes an async function along with await axios.all: async handleSubmit(){ const ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

Tips for inserting HTML-tagged data into a database using AJAX and PHP

var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); function submitData(){ var id=$("#id").val(); var status=$("#status").val(); var jtitle=$("#jtitle").val(); var jdesc=tinyMCE.acti ...

Using directive to access service values directly

I am in need of utilizing a directive to fetch and display data using ng-repeat from a service. The anticipated result will be <ul>Days <li>Monday</li> <li>Tuesday</li> ... <ul> <ul>Month <li>January</li ...

Error: Unable to initialize VueRouter as a constructor

In my app.js, I have the code snippet below: const routes = [ {path:'/home', component:home}, {path:'/department', component:department}, {path:'/employee', component:employee} ] const router = new VueRouter({ ...

Exploring how to utilize Jest with timers for vee validate integration

I am faced with a challenge in determining if my button is disabled as the disabled property keeps returning undefined. I have carefully reviewed and followed the guidelines provided at , but unfortunately, it does not seem to work as expected. I suspect t ...

An unusual 'GET' request has been made to the '/json/version' endpoint in Express.js

Hey there, I'm facing a challenge with my Express project. For some reason, I keep receiving a 404 error due to a mysterious GET request to '/json/version'. The request seems to bypass the defined routers after adding session data and eventu ...

When using the * selector in jQuery on Chrome, it targets and selects scrollbars

Here's the code I'm currently using: $("*").bind("mousedown.sg", { 'self':this }, this.sgMousedown); This code binds an event listener to all elements on the page, and it functions properly in most browsers except for Chrome. In Chrom ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...