Skip to content

Instantly share code, notes, and snippets.

@aitee
Last active September 10, 2019 17:09
Show Gist options
  • Save aitee/3b2be3ad21514e2475c7854f5d621b1a to your computer and use it in GitHub Desktop.
Save aitee/3b2be3ad21514e2475c7854f5d621b1a to your computer and use it in GitHub Desktop.
fresh block
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.container {
display:inline-block; <!-- allows to shrink the div to the svg size -->
}
.tooltip {
color: white;
background:blue;
width:50px;
height:50px;
position: absolute;
}
.tooltip-left-right{
position: absolute;
}
.tooltip-root {
position: absolute;
top:0px;
left:15px;
}
.overlay {
width:500px;
height:300px;
position: absolute;
top:0px;
left:0px;
pointer-events:all;
}
body { background:black; margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { background: red; }
</style>
</head>
<body>
<div class="container" style="position:relative"></div>
<script>
var width = 500;
var height = 300;
var margin = 15;
var tooltipSize = 50;
var container = d3.select(".container");
var svg = container.attr("background-color", "black").append("svg")
.attr("fill", "#00000")
.attr("width", width)
.attr("height", height);
var isOnRight = true;
var tooltipRoot = container.append("div")
.attr("class", "tooltip-root")
.attr("background", "blue")
.attr("font-size", 36)
.attr("font-family", "monospace")
var tooltipLeftRight = tooltipRoot.append("div")
.attr("class", "tooltip-left-right");
var tooltip = tooltipLeftRight.append("div")
.attr("class", "tooltip")
;
tooltip.text("hi");
var drag = d3.drag()
.on("start", function (d) {
updateTooltipOffset(d3.event.x);
})
.on("drag", function (d) {
tooltipRoot.style("left", `${d3.event.x+margin}px`);
updateTooltipOffset(d3.event.x);
});
function updateTooltipOffset(x){
var wasOnRight = isOnRight;
console.log(x, margin)
var offset = 0;
if (x >= width - tooltipSize - margin){
isOnRight = false;
offset = - tooltipSize - 2*margin;
}
else{
isOnRight = true;
}
if (wasOnRight !== isOnRight)
{
//translate left/right on the rect itself
tooltipLeftRight.transition().duration(400).ease(d3.easeCubicOut)
.style("left", `${offset}px`);
}
}
var overlay = container.append("div")
.attr('class', 'overlay')
.call(drag);
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment