Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

javascript - D3: Prevent tooltip from going out of the box

I have some charts, like line and area charts but the tooltip is going out of the box container. Click here to check issue. Especially when it's in a mobile view. In this particular case, I want the tooltip to render to the left continuously when approaching the right border.

Below is the code. If any more additional info is needed, I'm pleased to share more. Thanks in advance!

    const body = document.body;
    const docElem = document.documentElement;
    const scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
    const scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
    const clientTop = docElem.clientTop || body.clientTop || 0;
    const clientLeft = docElem.clientLeft || body.clientLeft || 0;
    //var y = box.top +  scrollTop - clientTop;
    let y = d3.event.clientY + scrollTop - clientTop;
    let x = d3.event.clientX + scrollLeft - clientLeft;
    const tooltipWidth = tooltip.width();
    const tooltipHeight = tooltip.height();
    x = (x > tooltipWidth / 2 + 16) ? x - tooltipWidth / 2 : 16;
    y = (y < tooltipHeight + 30 + 3.5) ? 5 : y - tooltipHeight - 25 - 3.5;
    tooltip
      .css('left', Math.max(0, x) + 'px')
      .css('top', y + 'px');

Additional code for understanding where some values come from:

// show tooltip
  const tooltip = $('div.widget-tooltip');
  let tooltipText = '';
  ...
  tooltip.html(tooltipText);
  tooltip.show().css('opacity', 1);
question from:https://stackoverflow.com/questions/65598796/d3-prevent-tooltip-from-going-out-of-the-box

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...