Enhancing Google charts with vertical line effects on hover

I am currently working on a project using google line charts and an angularjs directive. I am trying to figure out how to display vertical lines on hover, similar to how it is done on Google Trends, instead of having fixed lines. However, I have not been able to find a solution for this yet.

This is what I am attempting to achieve:

https://i.sstatic.net/3BGDA.jpg

I have managed to hide the vertical lines, but I cannot get them to appear on mouse hover. Here are the options I am using for the angular-google-chart directive:

options: {
  vAxis: {
    title: 'My title',
    gridlines: {
      count: 10
    }
  },
  hAxis: {
    title: 'title hAxis',
    gridlines: {
      color: 'transparent'
    }
  }
}

Answer №2

There are no standard configuration options for this specific feature, however, you have the option to include a custom line on hover for enhanced user interaction. Check out the provided snippet below for a demonstration:

google.charts.load('current', {
  callback: drawChart,
  packages: ['corechart']
});

function drawChart() {
  // Code for drawing the chart goes here
}
// Additional code for hover line functionality goes here

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Answer №3

Include the following code snippet:

focusTarget: 'category',
crosshair: {orientation: 'vertical', trigger: 'focus'},

in your configuration options.

Here is an example:

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawLogScales);

function drawLogScales() {
      var data = new google.visualization.DataTable();
      data.addColumn('number', 'X');
      data.addColumn('number', 'rate');
      
      // Data rows omitted for brevity
           
      var options = {
        focusTarget: 'category',
        crosshair: {orientation: 'vertical', trigger: 'focus'},
        hAxis: {
          title: 'day',
          logScale: false
          
        },
        vAxis: {
          title: 'rates',
          logScale: false
          
        },
        colors: ['#a52714', '#097138']
      };
        
      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
      chart.draw(view, options);
    }
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <div id="chart_div"></div>

Refer to lines 22,23

Answer №4

Shoutout to the talented @WhiteHat for the inspiration in his previous response, where I've modified his code to integrate it seamlessly with angular-google-charts in an angular 1.5 component. Here's my unique approach:

Angular-google-charts provides several directives for attaching custom events like mouseover, mouseout, ready, and more. For instance:

<div google-chart agc-on-mouseover="$ctrl.onMouseOver(row, column)"
       chart="$ctrl.data" agc-on-ready="$ctrl.onReady(chartWrapper)" agc-on-mouseout="$ctrl.onMouseOut(row, column)">
</div>

Notably, I have included agc-on-ready, agc-on-mouseover, and agc-on-mouseout directives to seamlessly bind my custom functions to these events.

Building upon the solutions proposed by @WhiteHat, my custom functions are outlined below:

self.onMouseOver = function (row, column) {
    if (row !== null) {
        var dataTable = self.chartWrapper.getDataTable();
        var xPos = self.layout.getXLocation(dataTable.getValue(row, 0));
        self.svgParent.appendChild(self.hoverLine);
        self.hoverLine.setAttribute('x', xPos);

        // This line ensures correct positioning of the line under the tooltip     
        self.svgParent.insertBefore(self.hoverLine, self.svgParent.children[4]);
    }
}

self.onMouseOut = function (row, column) {
    if (row !== null) {
        self.svgParent.removeChild(self.hoverLine);
    }
}

self.onReady = function (chartWrapper) {
    // Define variables for drawing the vertical line on hoverLine  
    self.chartWrapper = chartWrapper;

    // Obtain the container using chartWrapper.getContainerId()
    var container = angular.element(chartWrapper.getContainerId());
    self.svgParent = container[0].getElementsByTagName('svg')[0];
    self.layout = chartWrapper.getChart().getChartLayoutInterface();
    self.lineHeight = self.layout.getBoundingBox('chartarea').height - 18;
    self.lineTop = self.layout.getBoundingBox('chartarea').top;

    self.hoverLine = container[0].getElementsByTagName('rect')[0].cloneNode(true);
    self.hoverLine.setAttribute('y', self.lineTop);
    self.hoverLine.setAttribute('z', 100);
    self.hoverLine.setAttribute('height', self.lineHeight);
    self.hoverLine.setAttribute('width', '1');
    self.hoverLine.setAttribute('stroke', 'none');
    self.hoverLine.setAttribute('stroke-width', '0');
    self.hoverLine.setAttribute('fill', '#cccccc');

};

I trust you'll find this implementation beneficial and welcome your feedback for further enhancements.

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

how to adjust the width of table columns dynamically using ng-repeat and AngularJS

Working on a user interface that contains a table where the column widths adjust according to percentage data. I'm using ng-repeat to populate the table, but need help setting unique widths for each piece of data received. Here's some of my Angul ...

Implications of using literals, objects, or classes as arguments in functions that are called multiple times can have

Context A project I'm working on involves a scenario where a Shape class is triggering a function call SetPosition( x, y ) on a Drawer class. As part of this process, the Drawer class needs to retain the values (x, y) passed through SetPosition. The ...

Interactive Communication: PHP and JQuery Messaging Platform

I am developing a social networking platform and I am looking to integrate a chat feature. Currently, I have a home.php page that displays a list of friends. The friends list is loaded dynamically using jQuery and PHP, like this: function LoadList() { ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

How to properly implement search functionality in a React table?

I recently implemented a search feature for my table in React to filter items fetched from an external API. Instead of making repeated calls to the API on each search, I decided to store the retrieved data in two separate useState hooks. One hook holds th ...

Example of Using Python and Ajax Together: How to Send a Response using Python?

Exploring the code with Python and Javascript to set up an Ajax system. Essentially, the goal is to input a word and have the Python code send it back. Here is the HTML/JavaScript snippet: <html> <head> <title>Simple Ajax Example</tit ...

Retrieve Data from HTML Table using jQuery

I am working with an HTML table that has the following values: <tr class="tuker1"> <td class="tuker-lft1"> Username </td> <td class="tuker-rght1" onclick="awardRoute()"> <a href="#"> AWARD ROUTE </ ...

PhantomJS version 2.1.1 encountered an error on a Windows 7 system, displaying "ReferenceError: Map variable not found."

I've been utilizing the "MVC ASP.NET Core with Angular" template. I'm attempting to incorporate phantomJS and execute the tests, but encountering the following errors: ERROR in [at-loader] ..\\node_modules\zone.js\dist&bs ...

Establishing a Table of Disarray

I've hit a roadblock and I'm feeling confused about where to go next. Currently, I'm exploring the use of JavaScript to create tables for my data and display them in HTML. While I've successfully created the HTML table, I'm facing ...

Struggling to retrieve the data from a RESTful API?

I'm currently learning how to fetch an API in javascript and I'm encountering some difficulties in extracting specific parts of the response body. My goal is to store the setup and punchline of a joke in variables for later use. Here is the code ...

Discover the process of converting the texture in three.js to WebGL

I have received two texture objects containing position and normal data: var tx1 = gpuCompute.getCurrentRenderTarget( positionVariable ).texture; var tx2 = gpuCompute.getCurrentRenderTarget( normalVariable ).texture; These textures are generated using GP ...

Creating an effective follow-following system in Node.js

I have built a Node.js application that features a basic follow system, allowing users to receive the latest articles from those they follow. The current implementation involves creating an array called followers, which stores the userIDs of all users fol ...

Unable to assign values to textarea and checkbox in MVC5

I am currently facing an issue with setting values in JavaScript + jQuery in MVC 5 for textareas and checkboxes. Here is the JavaScript code I am using: document.getElementById("UpdatetxtDescription").value = "abc"; document.getElementById("Upda ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...

I'm having trouble getting onClick to function properly in CodeIgniter

While attempting to utilize onClick in the PHP page as shown below: <a href="javascript:void(0);" onClick="deleteCourse('<?php echo $row->courseId;?>');" class="delete">Delete</a> And in the JavaScript page, the function is ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

Error in cloned selections with bootstrap-selectpicker showing one less item

When duplicating a bootstrap-select dropdown, the duplicate dropdown appears to be offsetting selections by 1. For example, if the second option is clicked, the first one is actually selected. Here is an illustration: If "New Castle" is clicked in the ...

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

In order to extract a value from a different webpage, I must first make a request to that webpage and extract the XML value from it

I have been working on a project that requires displaying currency exchange rates. To achieve this, I initially tried using AngularJS to call another webpage for the exchange rate values, but I encountered issues as AngularJS can only make JSON/Rest URL ca ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...