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.
2 Answers 2
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 thedisplay
value (you can transparently change it to something other thanblock
)
and so:
$('div.a')
.mousemove(function(e){
$('#follow').offset({
left: e.pageX + 20,
top: e.pageY
});
})
.hover(function() {
$('#follow').show();
}, function() {
$('#follow').hide();
})
Fiddle: http://jsfiddle.net/ycqx58ka/1/
-
\$\begingroup\$ mousemove is not a shortcut for .bind('mousemove'), Bind is applicable only if dom is not visible. \$\endgroup\$Paritosh– Paritosh2014年08月14日 17:00:25 +00:00Commented Aug 14, 2014 at 17:00
-
-
\$\begingroup\$ My mistake sorry \$\endgroup\$Paritosh– Paritosh2014年08月14日 18:06:11 +00:00Commented Aug 14, 2014 at 18:06
-
\$\begingroup\$ -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." \$\endgroup\$Schism– Schism2014年08月14日 19:01:36 +00:00Commented Aug 14, 2014 at 19:01 -
\$\begingroup\$ @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 \$\endgroup\$blgt– blgt2014年08月14日 21:47:48 +00:00Commented Aug 14, 2014 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');
})