# Compact jQuery tool tip code, without jQueryUI

I have this tooltip code that I came up with, using jQuery:

$('div.a') .bind('mousemove', function(e){$('#follow').css({
left:  e.pageX + 20,
top:   e.pageY
});
})
.mouseenter(function() {
$('#follow').css('display','block'); }) .mouseleave(function() {$('#follow').css('display','none');
})


I was wondering if there is anyway to compact it even more than it already is (ignore whitespace).

Here is a jsFiddle, if you'd like to test it.

Your code is already pretty clean, and makes it easy to see what you're doing. What I can suggest is replacing some of the function calls with jQuery's shortcuts:

• .mousemove is a shortcut for .bind('mousemove')
• .offset is (in this case only) a more specific version of .css
• .hover is a shortcut for both .mouseenter and .mouseleave
• .show and .hide are shortcuts for .css('display'); additionally they abstract away the handling of the display value (you can transparently change it to something other than block)

and so:

$('div.a') .mousemove(function(e){$('#follow').offset({
left:  e.pageX + 20,
top:   e.pageY
});
})
.hover(function() {
$('#follow').show(); }, function() {$('#follow').hide();
})

• mousemove is not a shortcut for .bind('mousemove'), Bind is applicable only if dom is not visible. – Paritosh Aug 14 '14 at 17:00
• @paritosh Unless I'm reading this wrong, that's exactly what it is; ref. line 2599 – blgt Aug 14 '14 at 17:12
• My mistake sorry – Paritosh Aug 14 '14 at 18:06
• -1: .offset() is not equivalent to .css(). .css() is relative to the nearest positioned element, while .offset() is relative to the document. .offset() is also significantly slower because of the calculations required. These details should be explained, instead of the rather vague "in this case only." – Schism Aug 14 '14 at 19:01
• @Schism For the setup in the fiddle, they absolutely are equivalent. I prefer .offset as it's clearer and cleaner. For other cases (corner?), .offset is actually also more robust. As for being slower -- yes, you're right there, when rendering speed matters straight css becomes preferable – blgt Aug 14 '14 at 21:47

Bind method should be used only when if your element is not loaded into DOM on pageload. So you could attach events to it using bind after wards. also if your using jquery >= 1.7 use 'On' method to achive it. but as per your js fiddle you don't need it at all.

second you could declare a variable to store the jquery object of follow. Make sure about the variable scope though.

var follow=$('#follow');$('div.a').mousemove(function(e){
follow.css({
left:  e.pageX + 20,
top:   e.pageY
});
})
.mouseenter(function() {
follow.css('display','block');
})
.mouseleave(function() {
follow.css('display','none');
})