Skip to content

Instantly share code, notes, and snippets.

@tmtk75
Created January 9, 2017 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmtk75/ff1fac94db8c1bc3ded34f40678fda47 to your computer and use it in GitHub Desktop.
Save tmtk75/ff1fac94db8c1bc3ded34f40678fda47 to your computer and use it in GitHub Desktop.
Detection hover more than 500 milliseconds with RxJS
<!DOCTYPE html>
<html lang="en">
<head>
<style type="text/css">
#main { display: flex; flex: 1; }
.node { border: 1px solid gray; width: 160px; height: 100px; margin: 1px; }
.node:hover { background-color: rgba(0, 0, 0, 0.1); }
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.1/Rx.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="main"></div>
<textarea id="out"></textarea>
</body>
<script>
d3.select("#main").selectAll("div")
.data(["a", "b", "c"])
.enter()
.append("div")
.attr("class", "node")
.text((e) => e)
</script>
<script>
const t = document.querySelectorAll("body .node")
console.log(t)
const enter = Rx.Observable.fromEvent(t, "mouseenter")
const leave = Rx.Observable.fromEvent(t, "mouseleave")
const move = Rx.Observable.fromEvent(t, "mousemove")
const entered = enter.map(e => true).merge(leave.map(e => false))
move
.combineLatest(entered)
.debounceTime(500)
.filter(([e, b]) => b)
.map(([e, _]) => e)
.do(console.log)
.subscribe(e => out.innerText = e.target.innerText)
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment