There is another question on stackoverflow concerning searching for nodes here. I would love to have this for my network, however due to its size (> 1000 nodes) a highlighting won't work. Well it works, but the nodes are quite small and thus when there is only one node visible its really hard to spot this on a whole screen. Therefore I want the search function to zoom in on the node instead. I will copy and paste the answer code from the other question here:
library(htmltools)
library(networkD3)
data(MisLinks)
data(MisNodes)
# make a forceNetwork as shown in ?forceNetwork
fn <- forceNetwork(
Links = MisLinks, Nodes = MisNodes, Source = "source",
Target = "target", Value = "value", NodeID = "name",
Group = "group", opacity = 0.4, zoom = TRUE
)
fn <- htmlwidgets::onRender(
fn,
'
function(el,x){
debugger;
var optArray = [];
for (var i = 0; i < x.nodes.name.length - 1; i++) {
optArray.push(x.nodes.name[i]);
}
optArray = optArray.sort();
$(function () {
$("#search").autocomplete({
source: optArray
});
});
d3.select(".ui-widget button").node().onclick=searchNode;
function searchNode() {
debugger;
//find the node
var selectedVal = document.getElementById("search").value;
var svg = d3.select(el).select("svg");
var node = d3.select(el).selectAll(".node");
if (selectedVal == "none") {
node.style("stroke", "white").style("stroke-width", "1");
} else {
var selected = node.filter(function (d, i) {
return d.name != selectedVal;
});
selected.style("opacity", "0");
var link = svg.selectAll(".link")
link.style("opacity", "0");
d3.selectAll(".node, .link").transition()
.duration(5000)
.style("opacity", 1);
}
}
}
'
)
browsable(
attachDependencies(
tagList(
tags$head(
tags$link(
href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css",
rel="stylesheet"
)
),
HTML(
'
<div class="ui-widget">
<input id="search">
<button type="button">Search</button>
</div>
'
),
fn
),
list(
rmarkdown::html_dependency_jquery(),
rmarkdown::html_dependency_jqueryui()
)
)
)
I have looked around at bl.ocks.org and found something that could work here. Especially this piece of code:
svg.transition()
.duration(750)
.call(zoom.translate(translate).scale(scale).event);
I thought I could simply insert it here:
………………>
selected.style("opacity", "0");
svg.transition()
.duration(750)
.call(zoom.translate(translate).scale(scale).event);
This does not seem to work, and with limited knowledge of JavaScript I can't get it to work either. Besides the solution, a short explanation would be appreciated!