views:

21

answers:

1

I have created a tooltip that appends a DIV with text to the page.

I have managed to get it to appear in the position i want and follow the mouse as it moves.

I was previously doing this with inline styles and updating the top, left absolute positioning co-ordinates dynamically inline.

This seems to cause performance issues so i wrote the dynamic styling to a <style> in the <head> of the dosument which works fine in Firefox but now not in IE7 or IE6.

The jsFiddle is here;

http://jsfiddle.net/SBhnc/7/

I guess i need to remove the tag from the on mouseout as well but IE seems to render it once and then always again in the same position.

I would obviously like it to work in all browsers and not suffer any massive performance hits like it was when writing inline styles.

+2  A: 

Not sure exactly where to start, so how about my changes? As you can see, it now works just fine in Internet Explorer. Explanations for each change:

  • Internet Explorer allows a maximum number of StyleSheets (31 or 32, I think) and on your mousemove event you were appending a new <style> element to the head. When it reaches the limit the tooltip never moves again. I switched it back to css() for you.
  • Every time you mouseover the elements, you attach a new mousemove event. The problem here is that you never unbind this handler, so mouse off, mouse on causes a new handler to be attached each time, doubling the work being done and over-stressing the browser (poor IE!). I moved the mouseover handler to it's own space where it's only created and attached once.
  • Each mouseover would create the tooltip, then on mouseoff you detach it. Much better to have it in the DOM to start with, just hide() and show() it.
  • You don't do any caching of selectors or variables. Each time you write $('#tooltip') it's an extra lookup. Save the result of $('#tooltip') to a variable and use the variable.

I did some of the work caching $('#tooltip'), but you should do the same for $(this). mousemove is a fairly stressful event, and can be called many times within a few ms. This causes slowdown on the rendering because it waits for the script to complete.

Andy E
that's great Andy. Really appreciated. As much as i am learning about actually writing the code it really helps to know how to optimise it as well and this has been a valuable insight.
RyanP13
@Ryan: no worries :-) You might also want to look at implementing your tooltip as a plugin, which would make it a little more portable. Search Google for "jQuery plugin tutorial" and you should be able to find something to get you started.
Andy E