How to turn a label into a link (canvas version)

This document shows you how, when using the textAccessible option, to turn one of your labels into a functioning link that you can click.

A Bar chart with a linked label
[No canvas support]

This HOWTO document tells you how you can, when using the textAccessible option (which RGraph does by default), easily turn a bit of text into a link. The mwthos uses jQuery but you should be able to easily adapt it to your own preferred JavaScript library.

Getting hold of the relevant bit of text

The first thing that you need to do is get a reference to the bit of text that you wish to turn into a link. By using the RGraph.text2.find() function this is made very easy. The function returns the DOM node which you can then manipulate.

    var text = RGraph.text2.find({
        id: 'cvs',
        text: /james/i

The function can accept a few different search criteria to find the relevant bit of text - but in this case its using the text option which can be a regular expression to match the text with. You'll fnd the other options documented in the canvas API documentation here

The RGraph.text2.find() function returns an array of <span> tags that match the specified search criteria. So here, the function returns an array of just a single <span> tag.

Setting the style of the tag

Now that we have the <span> tag we can set some style on it as required. Here I've used jQuery (because it makes it nice and easy to do so) but you don't have to. Indeed if you have a preferred library then you can use that instead because the <span> tag node is just a normal HTML node.

    // Use jQuery to wrap the text in a link
    $(text[0]).wrap('<a href="" target="_blank"></a>')
    // Make the text look like a link
        color: 'blue',
        fontWeight: 'bold'

You can see the results in the labels of the chart above - one of the labels is made to be a link and will take you to Google.

See also