Issue arises when annotation is utilized in ChartJs, as the tooltip fails to appear

Upon hovering over a dot, only a blue line is displayed without showing a tooltip as expected below:
Library Version:
"chart.js": "^2.9.3", "chartjs-plugin-annotation": "^0.5.7"

Actual : enter image description here
Expected: enter image description here

In chart configuration

 export chart = () => {
         data:{ ... }, 
         options: {
             tooltips: {
              displayColors: false,
              mode: 'index', intersect: true,
              callbacks: {
                label: function (tooltipItem, data) {
                  return `${data.datasets[tooltipItem.datasetIndex].label}(${Math.round(tooltipItem.xLabel * 100) / 100
                    },${Math.round(tooltipItem.yLabel * 100) / 100})`;
                },
              },
            },
            legend: {
              display: false,
            },
            annotation: {
              drawTime: "afterDatasetsDraw",
              events: ["mouseover"],
              annotations: [],
            },
        }
    }

convertToHoverLine();

export const convertToHoverLine = (value, scaleID) => {
  return {
    key: "hoverLine",
    type: "line",
    mode: "vertical",
    scaleID,
    value,
    borderColor: "blue",
    onMouseout: null,
    onMouseover: null,
  }
}

handleHoverChart(); => this function will trigger when a user hover a dot on the chart

   export const handleHoverChart = (myChart, x, scaleID) => {
         const indexLine = myChart.options.annotation.annotations.findIndex(i => i.key === "hoverLine")
         if (indexLine === -1) {
            myChart.options.annotation.annotations.push(convertToHoverLine(x,scaleID))
         } else {
           myChart.options.annotation.annotations[indexLine] = convertToHoverLine(x,scaleID);
           }
  myChart.update()
}

Answer №1

The solution I implemented involved moving the chart update into a specific condition.

const updateChartOnHover = (chart, xValue, scaleIdentifier) => {
       const indexOfHoverLine = chart.options.annotation.annotations.findIndex(item => item.key === "hoverLine")
       if(indexOfHoverLine === -1){   
           chart.options.annotation.annotations.push(createHoverLine(xValue, scaleIdentifier))
           chart.update()
        } else {
              chart.options.annotation.annotations[indexOfHoverLine] = createHoverLine(xValue, scaleIdentifier);
             }
 }

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

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Testing Vue with Jest - Unable to test the window.scrollTo function

Is there a way to improve test coverage for a simple scroll to element function using getBoundingClientRect and window.scrollTo? Currently, the Jest tests only provide 100% branch coverage, with all other areas at 0. Function that needs testing: export de ...

Arranging an array based on relationships between children and parents

I have an array of objects like this: const data = [{id: 3, name: ''}, {id: 4, name: ''}, {id: 5, name: '', parent: 3}, {id: 6, name: '', parent: 5}, {id: 7, name: '', parent: 4}, {id: 8, name: '&ap ...

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :. Here is the current code snippet from our config/dev.env.js, and I&a ...

Enhancing data management with Vuex and Firebase database integration

Within my app, I am utilizing Firebase alongside Vuex. One particular action in Vuex looks like this: async deleteTodo({ commit }, id) { await fbs.database().ref(`/todolist/${store.state.auth.userId}/${id}`) .remove() .then ...

"Using JavaScript to find and manipulate objects within an array by either removing them or adding

I'm struggling to manipulate an array by either removing or adding an object based on its existence. I've attempted using both a for if loop and forEach loop but haven't been successful. Here's my current approach: // Object in ...

Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to prev ...

Vue select component not refreshing the selected option when the v-model value is updated

Trying to incorporate a select element into a Vue custom component using the v-model pattern outlined in the documentation. The issue at hand is encountering an error message for the custom select component: [Vue warn]: Avoid directly mutating a prop as i ...

Exploring the capabilities of a Vue.js component

I am currently facing some challenges while trying to test a Vue.js component. My main issue lies in setting a property for the component and verifying that it has been set correctly. For context, the module has been loaded with exports and the JavaScrip ...

Vue 3 feature: Click the button to dynamically insert a new row into the grid

Just starting out in the world of coding, I've zero experience with Vue - it's my introduction to frameworks and arrays are currently my nemesis. In a recent exercise, I managed to display the first five elements of an array in a table after filt ...

Exploring the World of Vue.js Object Imports

I am currently encountering an issue involving the importing of Objects from App.vue into a component. To provide context, this project consists of a Navigation Drawer component and an App.vue file. The Navigation Drawer contains Vue props that can be dyna ...

Activate a tooltip in Vuetify

I'm utilizing vuetify and have implemented a tooltip feature on a button. However, I do not want the tooltip to be displayed on hover or click; instead, I would like it to appear when a specific event is triggered. translate.vue <v-tooltip v-model ...

Creating a radial progress chart using Plotly JavaScript

I recently started working with the Plotly library and now I need to display a circular progress graph in Vuejs 2, like the one shown below. While Plotly is a comprehensive tool, I have not come across an example that matches this specific design using Ja ...

Use the Vue `this.$router.push` method inside a setTimeout function

I have a landing page '/' that users will see first when they visit our website. I want to display a loading wheel for 5 seconds before automatically redirecting them to the login page '/login'. My Landing.vue page in Vue and Bulma.io ...

display different vue component based on screen size

I am in search of a method to implement responsive components in Vue.js (Nuxt). I have developed this mix-in but encountering an error: export const mediaQuery = { data() { return { breakpoints: { sm: 576, md: 768, lg: ...

Sending information to a single component among several

I'm developing a custom DownloadButton component in VueJS that features an animation when clicked and stops animating once the download is complete. The DownloadButton will be utilized within a table where it's replicated multiple times. I intend ...

What is the process for adding parameters to a Fetch GET request?

I have developed a basic Flask jsonify function that returns a JSON Object, although I am not certain if it qualifies as an API. @app.route('/searchData/<int:id>',methods=["GET"]) def searchData(id): return jsonify(searchData(id)) Curr ...

Unexpected token error occurs when using map-spread operator in vue-test-utils combined with jest

I recently set up testing for my Vue project by following the instructions provided in this helpful guide here Upon completion of the guide, I proceeded to create a test for one of my components. However, when I ran jest, I encountered the following error ...