How to get the X axis value of your AMChart using jQuery.mousemove event?

Sometimes we want to capture the X axis (Category axis) value of our AMChart StockChart from our mouse position and display it anywhere in our page.  Apparently AMChart StockChart does not support such event.   What they recently did to solve the issue is to create a chartCursor (see turtorial), which I find it hard to implement because I normally have multiple panels and graphs in my StockChart object.

My solution and approach to the problem is to use jQuery.mousemove event, as shown in the JS code below:

$("#chartdiv").mousemove(function (event) {
    // Implement here...

You need to access event.PageX/Y and event.ClientX/Y to get the pixel position of the mouse. But this will get you into trouble when you are using IE, don’t worry! there is a solution, see the code below, this code fixes the pixel position if you are using IE (for more details visit this page).

function fixPageXY(e) {
    if (e.pageX == null && e.clientX != null) {
        var html = document.documentElement
        var body = document.body

        e.pageX = e.clientX + (html.scrollLeft || body && body.scrollLeft || 0)
        e.pageX -= html.clientLeft || 0

        e.pageY = e.clientY + (html.scrollTop || body && body.scrollTop || 0)
        e.pageY -= html.clientTop || 0

Once you have the pixel position of the mouse, you can now extract the X axis (Category axis) value of your chart by using xToIndex method of the categoryAxis see the code below.  The xToIndex method also solves the position of the mouse when you zoom the chart (cool eh!).

var xValue = stockPanel1.categoryAxis.xToIndex(event.pageX.toFixed()-228);

Remember to round-off the pixel position by using .toFixed() and then calibrate the value base on your page layout,  in my example code, I need to adjust the pixel position by 228 pixels because I am using a sidebar.  So the final code will look like this:

$("#chartdiv").mousemove(function (event) {
      event = event || window.event;

      var xValue = stockPanel1.categoryAxis.xToIndex(event.pageX.toFixed()-228);

      // Do your DOM manipulation here...

In the image below, the blue sidebar now corresponds to the X axis (Category axis) of the chart.



That’s it.  Happy coding and if you find this blog helpful, you can make the donation by clicking the Paypal button below.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s