How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneously. The situation involves an unordered list of links and I'm utilizing a computed value to dynamically alter the inline styles when hovering over the links:

This is how my component looks like:

      <section class="categoryList">
        <ul>
          <li v-for="category in categories" :key="category.id"&g
            <a
              @mouseenter.stop="mouseOver()"
              @mouseleave.stop="mouseOver()"
              class="category"
              :style="getStyle"
              href="#"
              @click.prevent="getCategory(category.name)"
              >{{ category.name }}</a
            >
          </li>
        </ul>
      </section>

This is the computed value used:

const getStyle = computed(() => {
  if (props.primaryColor != undefined && props.primaryColor != "") {
    if (!hover.value) {
      return `background-color:${props.primaryColor};color:${props.secondaryColor}`;
    } else {
      return `background-color:${props.secondaryColor};color:${props.primaryColor}`;
    }
  } else {
    if (!hover.value) {
      return `background-color:#614EFB;color:white`;
    } else {
      return `background-color:#523dfa;color:white`;
    }
  }
});

Additionally, there's a function that controls the hover state dynamically:

function mouseOver() {
  hover.value = !hover.value;
}

Answer №1

It seems like you can enhance the functionality by setting hover as an id rather than a boolean:

const { ref, computed } = Vue
const app = Vue.createApp({
  setup()  {
    const props = ref({primaryColor: null, secondaryColor: null})
    const categories = ref([{id: 1, name: 'aaa'}, {id: 2, name: 'bbb'}, {id: 3, name: 'ccc'}])
    const hover = ref(null)
    function mouseOver(id) { hover.value = id; }
    function mouseExit() { hover.value = null }
    getCategory = () => {}
    const getStyle = (id) => {
      if (props.primaryColor != undefined && props.primaryColor != "") {
        if (id !== hover.value) {
          return `background-color:${props.primaryColor};color:${props.secondaryColor}`;
        } else {
          return id === hover.value && `background-color:${props.secondaryColor};color:${props.primaryColor}`;
        }
      } else {
        
if (id !== hover.value) {
          return `background-color:#614EFB;color:white`;
        } else {
          return `background-color:red;color:white`;
        }
      }
    };
    return { props, categories, mouseOver, getStyle, getCategory, hover, mouseExit }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <section class="categoryList">
  <ul>
    <li v-for="category in categories" :key="category.id">
      <a
        @mouseenter="mouseOver(category.id)"
        @mouseleave="mouseExit()"
        class="category"
        :style="getStyle(category.id)"
        href="#"
        @click.prevent="getCategory(category.name)"
        >{{ category.name }}</a
      >
    </li>
  </ul>
  {{hover}}
</section>
</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

Is the tab not displaying correctly when using Bootstrap 5 button functionality?

With Bootstrap 5, I have a modal that contains two tabs for login and register. However, I am facing an issue where the tab is not displaying correctly based on the button click. The desired behavior is that clicking on the login button should activate th ...

Selection List dictates the necessity of JavaScript

I need to create a JavaScript code that will require the comment field (textarea) when a selection is made from a list. Currently, I have added a required icon next to the comment section but I am stuck at this point. See the code below. Thank you in adva ...

tips for optimizing pdf size using nodeJs and vueJs

I am searching for a library for either NodeJS or VueJS that can help reduce the size of PDF uploads by users. Which library should I choose? Alternatively, I came across pdftron but it is not widely used and not free. I tried installing ghostscript4js ...

Choose a random cell in Jquery every second

I am searching for a method to choose one div out of sixteen and change its CSS backgrounds. This selection needs to occur every second, so a new div is selected from the group each second. I am struggling with implementing the "every second" functionalit ...

skip every nth element in the array based on the specified value

The Challenge I'm currently working on a graph that relies on an array of data points to construct itself. One major issue I've encountered is the need for the graph to be resizable, which leads to the necessity of removing certain data points ...

"Reduce the height and adjust the row spacing of the Vuetify form for a more

I'm currently working on creating a form using vuetify that closely resembles the one shown in this image: https://i.sstatic.net/4h6YM.png After experimenting with vuetify grid and columns, I've managed to achieve something similar to this: http ...

Having trouble changing the state within React's useEffect() when using an empty dependencies array? Socket.io is the cause

I have a question regarding the access of allUserMessages from my state within useEffect without anything in its dependency array. Let me provide more details below. Thank you. My goal is to append data to an array in my state using useEffect similar to c ...

What is the best way to showcase search outcomes using ajax in a Django project?

In my current Django project, I am developing a feature that allows users to search for a name using a form. The view will then search for that name in the database after some transformation and display the results below the form. Currently, the entire pa ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

When initiating a new browser window with JQuery, some data is not being transmitted

Encountering an issue with the windows.open(); method. Tech Stack: Asp.netMVC, C#, Razor Problem: jQuery When the function is triggered, it should send parameters to the Actioid and taskid controllers. However, I am facing an issue where only Actioid and ...

Modify the button's color based on a separate column within the table

Currently, I am implementing Datatables along with X-editable and including some bootstrap buttons within a table. My objective is to change the color of the button in the 'Validated' column to green when the user updates the editable 'Statu ...

Struggling to locate the correct setup for .babel and react-hot-loader

I am currently utilizing babel 7. In their documentation, they specify that the new naming convention for plugins should include the @babel/ prefix. The recommended React-hot-loader babelrc configuration is as follows: { "plugins": ["react-hot-loader/ ...

Objects array - does not support the 'push' function

In my code snippet, it looks like this: var result = {}; for (var i = 0; i < questions.length; i++) { if(result.hasOwnProperty(questions[i].group)) { var questionsInGroup = result[questions[i].group]; log.debug(typeof questionsInGroup); ...

Examining - Assessing the Link (next/link)

I am currently working on writing unit tests to verify the functionality of my navigation links. Here is a snippet from my MainNavigation.js file: import Link from 'next/link'; const MainNavigation = () => { return ( <header> ...

jQuery ensures that the show and hide features happen instantly

I have a single div containing two other div elements: <div> <div id="card-container">....</div> <div id="wait-for-result-container" style="display: none;">...</div> </div> When a specific event occurs, I want to swi ...

Remove leading spaces before text

Is there a way to remove spaces before text only? " with spaces between" What I want: "some text with spaces between" I have tried using text.replace(/\s/g, '') but it doesn't give the desired result: "sometextwithspacesbe ...

Using React-router for server-side rendering and loading data with ajax calls

Currently I am working on implementing react-router in my project, but I seem to be facing some major concept misunderstandings. There are certain components in my application that require fetching data from the server. Previously, I used the following cod ...

Embed a local page into an HTML file using PhoneGap

I attempted to load a page within my phonegap application using Jquery .load(), but it isn't functioning because it's on a local machine rather than a server. When I eventually upload the app to PhoneGap Build, my page will still be located in th ...

Regular Expression - Invalid character detected in output

I'm currently in the process of developing a function to verify if a field is deemed acceptable based on a specific character set. In case it doesn't meet the criteria, I aim to determine and communicate which characters are not permitted. While ...

Tips for handling errors in ajax calls with alternative promises

While working on an application that offers weather data based on user location coordinates, I created the code provided below (also accessible in this codepen http://codepen.io/PiotrBerebecki/pen/QNVEbP). The user's location information will be retr ...