Custom tooltips and Microsoft’s chart control - Rohland's blog

Rohland's blog

Tech rocks!

Custom tooltips and Microsoft’s chart control

I have been meaning to blog about this topic for a while now because I am interested to find out if anyone else has picked up performance issues when using the Microsoft Chart Controls and the “MapAreaAttributes” property to create custom tooltips.

Before going into the mechanics of creating a custom tooltip as suggested by the documentation provided with the charting framework, I thought I would simply outline how you would create an instance of the default styled tooltip:

1 series.Points.DataBind(data,"X","Y","Tooltip=MyTooltipProperty");

The code above illustrates the databinding capabilities of the charting control. The data array is made up of a list of objects that are of type Point which is a simple class I created:

    1     public class Point

    2     {

    3         public double X {get;set;}

    4         public double Y { get; set; }

    5 

    6         public string MyTooltipProperty { get; set; }

    7 

    8         public Point()

    9         {

   10             this.MyTooltipProperty = "Hello!";

   11         }

   12     }

From the above it is obvious that each data point’s tooltip will look like something like this:

NormalTooltip

The tooltip is simply rendered using the relevant browser’s default implementation for elements.

Custom Tooltips:

You may be aware of the charting framework’s capability for creating rich HTML tooltips using the MapAreaAttributes property. As illustrated in an example provided with the framework you could create an HTML tooltip using code similar to that shown below:

series.Points[j].MapAreaAttributes = "onmouseover=\"DisplayToolTip('<strong>Hello From an HTML tooltip</strong>');\" onmouseout=\"HideTooltip();\""

The DisplayTooltip method referenced is a JavaScript method which essentially displays an absolutely positioned element which tracks your mouse position. The method is fired as you hover over the data point area (which is defined by an image area map). The parameter passed to the method is injected into the element as HTML. As you mouse out of the area (the relevant data point) the Hidetooltip method fires and hides the element displaying the custom tooltip. Using this methodology your tooltip could look something like this:

 htmltooltip

This looks promising because it illustrates the capability to extend our tooltips to include images, links etc. however, there is a caveat. I picked up an issue when you have a chart with a large number of data points, or a number of charts on a single page that utilise this feature. I started noticing that page loads took longer than usual. I put together a test page that rendered 40 instances of the same chart as shown above using the default tooltip. With tracing turned on the page took roughly 270ms to render:

defaultperf 

By implementing one extra line of code to implement my rich HTML tooltip using the MapAreaAttributes property as outlined earlier, the page took almost 5 seconds to render!

customperf 

It turns out anyone who dares to use the MapAreaAttributes property is severely penalised! Clearly we can’t put a page into production that takes 5 seconds just to render our charts, so we either need to revert to our dull looking tooltips or look for other ways to achieve rich HTML tooltip functionality.

Now, we know that setting the tooltip property doesn’t seem to have any performance impact but that it doesn’t result in a pretty looking tooltip either, but what if we could use the tooltip property to store the HTML tooltip markup. I know what your thinking:

Uglytooltip

Yuck. That will certainly have your users scratching their heads. So, what next? So far we know that using the example as provided by the charting documentation has an adverse affect on rendering times so that’s not ideal. Default tooltip styles work without performance issues but don’t allow us to render rich tooltips. Injecting HTML into the default tooltip property means our users need to slap on their XHTML goggles.

Well, there is an option available which I will outline here.  Essentially, it relies on the ability to interpret the default tooltip property and project it into a custom tooltip that we control. If we look at the HTML rendered by the chart control, you will notice an associated image map that looks something like this:

markup

As you can see, our HTML tooltip detail is sitting inside the title property, encoded of course. If we leave the mark-up untouched and hover over any element on the chart, the default tooltip is rendered with unparsed HTML. Thankfully, we can access this image map using JavaScript to rebuild the image map with mouseover/out events to render our custom tooltip. While this is exactly what setting the MapAreaAttributes property is supposed to do, modifying the rendered HTML to do the same thing bypasses the performance issue noted. I have provided the JavaScript method below which rebuilds the image map. All that is required, from a server side scripting point of view, is the registration of a start-up script to process any chart you wish to load with custom tooltips.

    1 RebuildImageMap: function(id) {
    2     // Fetch the image and grab the imagemap ID
    3     var map = $("#" + id).attr("usemap");
    4 
    5     // If the map ID is null, then perhaps there 
    6     // were no datapoints. Don't bother 
    7     // processing an empty set
    8     if (map == null)
    9         return;
   10 
   11     // Fetch the map element using jQuery and 
   12     // return the raw HTML element
   13     var areaMap = $(map)[0];
   14     if (areaMap == null) {
   15         return;
   16     }
   17 
   18     // Create an empty array to store our new elements
   19     var elementArray = [];
   20 
   21     // Iterate over existing map elements and create a new 
   22     // set with our mouseover/out events
   23     for (var i = 0; i < areaMap.areas.length; i++) {
   24         var oldAreaElement = areaMap.areasIdea;
   25         var element = document.createElement("AREA");
   26         element.shape = oldAreaElement.shape;
   27         element.coords = oldAreaElement.coords;
   28         
   29         element.tooltip = oldAreaElement.title;
   30         element.onmouseover =
   31             function() { DisplayTooltip(this.tooltip); };
   32         element.onmouseout = 
   33             function() { HideTooltip(); };
   34         element.href = oldAreaElement.href;
   35         elementArray[elementArray.length] = element;
   36     }
   37     // Get rid of the old map elements
   38     areaMap.innerHTML = '';
   39 
   40     // Add our new elements back in
   41     for (var i = 0; i < elementArray.length; i++) {
   42         areaMap.appendChild(elementArrayIdea);
   43     }
   44 
   45 }

The code above utilises jQuery which is useful, but not required to get the job done. If you are going to use another framework, just note that the map attribute (which contains the map’s ID) is prefixed with a #. You may want to get rid of that. The code above is a modified
snippet of an existing class. The DisplayTooltip method simply takes the tooltip HTML and loads it into a custom hidden element on the page. It then displays the element and tracks the mouse position so the element moves as the user’s cursor does. The HideTooltip method simply hides the tooltip and resets the HTML content. Using this technique, our HTML tooltip is rendered correctly without using the MapAreaAttributes  property.

 htmltooltip

So far I have tested this method of rendering custom tooltips in Firefox, IE 7/8 and Chrome. Its a pity that this was required in the first place. I am really not sure why setting the MapAreaAttributes  property has such a huge impact on rendering times. If anyone could shed light on the matter, please feel free to post the detail! For now, the implementation above will suffice. Since the image map processing is performed on the client side, there is no effect on the server side processing time.

Hope this helps someone out there.

Comments

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# June 22, 2009 4:13 PM

Clothing said:

Wow! Its imposible... I'm realy shocked :/

# September 6, 2009 11:40 PM

ggpnuliflc said:

fINdLg  <a href="uucjgettazed.com/.../a>, [url=http://fkuapqmusiqb.com/]fkuapqmusiqb[/url], [link=http://erazklwekurz.com/]erazklwekurz[/link], http://ahlznffbjocu.com/

# October 21, 2009 6:10 AM

Сенситив said:

Привет вам,дамы и господа. Сегодня всем нам показали эмблему надвигающейся в 2014 году Олимпиады, и я конечно не могу себе отказать в удовольствии нафлудить тут у Вас... :)

Итак, буквально по всем каналам прокатилось данное известие, как подобает, с наивысшей степенью ПиаРа. Сам президент показал нам логотипчик, замутили пресс-конференцию, на Первом забабахали концерт, ну и конечно, рекламные ролики о нашей необыкновенной Олимпиаде.

При этом как то на 2-й план отошла сама картинка, что будет красоваться на флагах, шарфиках, и прочей сувенирной продукции через 4 года. А хотелось бы остановиться на ней поподробнее. Откровенно говоря, когда увидел, был немного разочарован. Сразу всплыла в голове такая картина: сидят где-то наши организаторы Олимпиады, и тут один вскакивает с дивана и кричит "мужыки, нам ведь завтра эмблему в Олимпийский коммитет надо отсылать". Начинается суета, но не долго думая наши функционеры садятся за ближайший комп, набирают незамысловатым шрифтом фразу Sochi2014 (само собой на английском) добавляют банальное .RU А чтобы не заморачиваться с графикой, в поисковике находят олимпийские кольца и впихивают их рядом с этой надписью в фотошопе :)

Ребят, просто нет слов! Всё понимаю: кольца, название города, год проведения, но где тут фишка??? та, чтобы цепляла. Где нестандартные дизайнерские решения? Взять к примеру лого той же прошедшей Олимпиады 2006 года в Турине, где изображен силуэт “Моле-Антонеллины”, который нельзя перепутать ни с чем. Он плавно переходит в изображение горы, окруженной кристалликами льда, на которой снег сливается с небом. Кристаллики переплетаются между собой, образовывая сеть: сеть новых технологий и вечного Олимпийского единства.

Я вот совсем не понимаю, на кой нам нужно это .RU Посещаемость сайта решили повысить? так я думаю он и без эмблемы имел бы посетителей. К тому же официальный сайт олимпиады будет на английском и явно не в зоне RU. Да и вообще на фоне продвижения государством доменной зоны RF, как то уже начинаешь привыкать к мысли что зона RU вскоре станет "устаревшей" чтоли, а то и вообще сгинет как пережиток прошлого..

ЗЫ То ли ещё будет, весной талисман нужно миру показывать..

ЗЗЫ Простите за эмоции, высказался, успокоился.. :) А может не так уж он и плох? :)

# December 3, 2009 6:39 AM

Cherry said:

А вот знаете о чём я сейчас подумала.

10 дней на Новогодние каникулы - это очень много. Сперва как все обрадовалась, что одыхать полмесяца придётся. А вот как вспомнила прошлый год, и позапрошлый. Так что-то передумала. Подумайте сами, ни денег, ни здоровья не хватит. Опять головная боль, опять лишние калории, и опять весь год хождения в спортзал коту под хвост.

Ну что хихикайте? я не права??

# December 4, 2009 1:48 PM

ViCHa said:

Спешу поделиться новостью: обмен Яндекс.Денег на Вебмани и обратно больше официально не производится. Не знаю, какая их собака укусила, но сейчас обмен практически невозможен. Все крупные обменники, коими я пользовался переводы в данных направлениях просто не осуществляют. Порой приходилось с ЯД на WM переводить немалые суммы. И что теперь делать, ума не приложу.

Хорошо наверное тем, кто не пользуется электронной валютой, а по старинке - банковскими операциями, платёжками по факсу и тд)))

# December 14, 2009 1:14 PM

elkiigolkiq said:

Отличный и  безопасный мега бум, http://www.pi7.ru  

есть  всё! Чего нет. Создадим по вашей проcьбе.

<a href=http://www.pi7.ru/soft/>Программы</a>

:) и Анекдот от недосыпа Вопрос:

Почему в институте пары, а в школе уроки?

Потому что в школе учатся, а в институте паряться!!!

# January 17, 2010 3:23 PM

elkiigolkiq said:

Отличный и  безопасный мега бум, http://www.pi7.ru  

есть  всё! Чего нет. Создадим по вашей проcьбе.

<a href=http://www.pi7.ru/video/137-porno-video.html>порно видео</a>

:) и Анекдот от недосыпа В мединституте професор принимает экзамен у тупой студентки. Стучит себя по лбу:

- Ну! Вот здесь, где я стучу! Как эта кость называется?!

-... лобковая.

- М-да. Вы хоршо подумали? Еще раз спрашиваю, как называется эта кость?

- лобковая.

- Хорошо! Тогда ЭТО что, по вашему?!

И дергает себя за нос.

# January 18, 2010 1:18 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: