Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

clickout event #19

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Here's what's in the package:

#### selection.append / selection.insert

Appending and inserting with classes/ids
Appending and inserting with classes/ids

```js
selection.append("div.my-class");
Expand Down Expand Up @@ -86,3 +86,13 @@ var firstY = polygons.map(ƒ('points', 0, 'y'));
```

If you don't know how to type ƒ (it's [alt] + f on Macs), you can use ``d3.f()``, too. Also, [in @1wheel's blog](http://roadtolarissa.com/blog/2014/06/23/even-fewer-lamdas-with-d3/) you can read more about the rationale behind ƒ.

#### selection.on 'clickout' event

'clickout' triggers when you click outside of a hierarchy of nodes. It can be used for example to unselect a widget.

```js
d3.select('.container')
.datum('dummy')
.on('clickout', function(d){ console.log(this, d); });
```
26 changes: 25 additions & 1 deletion d3-jetpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,26 @@
// store d3.f as convenient unicode character function (alt-f on macs)
if (!window.hasOwnProperty('ƒ')) window.ƒ = d3.f;

// clickout function manager
function clickout(){
var callbacks = [];
document.querySelector('html').addEventListener('click', function(event){
for(var i=0; i<callbacks.length; i++){
var element = callbacks[i].container;
if(!element.contains(event.target)){
callbacks[i].callback.call(element, element.__data__);
}
}
});

return {
sub: function(_container, callback){
var container = typeof _container === 'string' ? document.querySelector(_container) : _container;
callbacks.push({container: container, callback: callback});
return this;
}
};
};
// this tweak allows setting a listener for multiple events, jquery style
var d3_selection_on = d3.selection.prototype.on;
d3.selection.prototype.on = function(type, listener, capture) {
Expand All @@ -142,7 +162,11 @@
for (var i = 0; i<type.length; i++) {
d3_selection_on.apply(this, [type[i], listener, capture]);
}
} else {
}
if(type === 'clickout'){
clickout().sub(this.node(), listener);
}
else {
d3_selection_on.apply(this, [type, listener, capture]);
}
return this;
Expand Down