开发者

jQuery: Floating info pop-up in the most elegant and efficient way

I want to implement a floating information pop-up (or how to call it), that appears when the cursor is over an element and stays within a fixed distance to the cursor. For instance something more less like here:

http://www.nytimes.com/interactive/2008/09/15/business/20080916-treemap-graphic.html

Say, I have 100 divs for which I want the pop-up to appear. I thought about doing it in two ways:

  1. For each div, in HTML code I have a hidden pop-up div, on mousemove I show it, move 开发者_StackOverflow社区to the cursor's position and on mouseleave I hide it. Each div has its mousemove (x100) and mouseenter event bound (x100).

  2. I have a single mousemove for the main area of the page,for each div on mouseenter and mouseleave I show / hide a pop-up. There is a single mousemove (x1) and mouseenter + mouseleave for each div (x100).

My questions are:

  1. Is This The Way? Or there is some better jQuery mechanism to use?

  2. Is there any difference in performance when I have a single mousemove and 100 mousemove callbacks?


floating information pop-up (or how to call it)

these are called tooltips (there are many javascript/jQuery plugins for these)

in regards to rolling your own, you seem to have it figured out, you'll need to create mouseover/mousemove/mouseout events for the divs. With jQuery this would look something like:

var $tooltip = $('#tooltip'), // reusable jQuery obj
    offset = {x: 20, y: 20}; // tooltip offset from the cursor

$('#container div').mouseover(function() { // over
    $tooltip.show()
}).mousemove(function(e) { // move
    // set the positioning with offset
    $tooltip.css({left: e.pageX + offset.x, top: e.pageY + offset.y}) 
    // set the tooltip HTML contents
    $tooltip.html('[your content]');
}).mouseout(function() { // out
    $tooltip.hide();
});

example jsfiddle

As for performance: jsperf - mousemove parent vs children

setting the mousemove event on the container does indicate a faster operations/sec in the above test case but in real world use it's unlikely you'd notice a difference.

here's an example where only the container's mousemove event is set

example jsfiddle #2


Have you just considered using premaid plugin for jquery like qTip ? http://craigsworks.com/projects/qtip2/download

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜