Question

Overall context: I have a db of cross-references among pages in a wiki space, and want an incrementally-growing visualization of links.

I have working code that shows clusters of labels as you mouseover. But when you move away, rather than hiding all the labels, I want to keep certain key labels (e.g. the centers of clusters).

I forked an existing example and got it roughly working.

enter image description here

Code that works at removing all labels:

i = j = 0;
if (!bo) { //bo=False - from mouseout
    //labels.select('text.label').remove();
        labels.filter(function(o) {
        return !(o.name in clicked_names);
        })
        .text(function(o) { return ""; });
        j++;
}

Code attempting to leave behind some labels, which does not work:

labels.forEach(function(o) {
    if (!(d.name in clicked_names)) {
        d.text.label.remove();
    }

I know I'm just not grokking the d3 model at all.... thx

Was it helpful?

Solution

The problem comes down to your use of in to search for a name in an array. The Javascript in keyword searches object keys not object values. For an array, the keys are the index values. So testing (d.name in clicked_names) will always return false.

Try

i = j = 0;
    if (!bo) { //bo=False - from mouseout
        //labels.select('text.label').remove();
         labels.filter(function(o) {
            return (clicked_names.indexOf(o.name) < 0);
            })
            .text(function(o) { return ""; });
            j++;

    }

The array .indexOf(object) method returns -1 if none of the elements in the array are equal (by triple-equals standards) to the parameter. Alternatively, if you are trying to support IE8 (I'm assuming not, since you're using SVG), you could use a .some(function) test.

By the way, there's a difference between removing a label and just setting it's text content to the empty string. Which one to use will depend on whether you want to show the text again later. Either way, just be sure you don't end up with a proliferation of empty labels clogging up your browser.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top