Forum Discussion

az2451's avatar
az2451
Resolver I
8 years ago
Solved

How to replace/remove SVG-Elements by using EventListener

 

Hi there,

 

im trying to figure out how to replace/remove svg-elements instead of creating new ones while using an eventListener.

 

when i move the slider handle to the right, it also moves the line. But for every step it creates new lines without removing the lines which were created before (i only want 1 line on my graph based on the slider handles position)

 

The start position was 50. i moved it to about 65:

 

 

 

I tried removing the child-elements by using:

d3.select("this.absline.parent").selectAll("*").remove();

 

but this didnt worked for me.

is there a index-value that i can access to remove all lines except for the newest one?

 

Or does somebody have a better solution for this?

 

here is my code:

 

 

// mySlider: HTML Range-Slider Element
this.mySlider.addEventListener("mousemove", (event) => { this.getx = parseInt((event.target as HTMLInputElement).value); // getx: number (gets the value based on the sliders handle position)
var rot = 1; // used to rotate the line
// SVG Line-Element var absline = this.g .append('g') .append('rect') .classed('bar', true) .attr("x", absx(this.getx)) // Position on the x-axis based on the "absx"-Scale .attr("width", 2) .attr("y", absy(d3.max(dat, function (d) { return d.counter }))) .attr("height", gHeight) .attr("transform", "rotate(" + rot + "," + absx(this.getx) + "," + absy(d3.max(dat, function (d) { return d.counter })) + ")"); });

 

 

 

  • At first , "this.absline.parent" is not correct. It seems you should use something like this:

     

    d3.select(this.absline.parent).selectAll("*").remove();

     

    We would also recommend not to remove/create an element for each event as adding/removing elements from DOM is a very expensive operation.

    It'd be better to keep a single element and change its position for each event.

     

    Ignat Vilesov,

    Software Engineer

     

    Microsoft Power BI Custom Visuals

    [email protected]

2 Replies

  • v-viig's avatar
    v-viig
    Community Champion

    At first , "this.absline.parent" is not correct. It seems you should use something like this:

     

    d3.select(this.absline.parent).selectAll("*").remove();

     

    We would also recommend not to remove/create an element for each event as adding/removing elements from DOM is a very expensive operation.

    It'd be better to keep a single element and change its position for each event.

     

    Ignat Vilesov,

    Software Engineer

     

    Microsoft Power BI Custom Visuals

    [email protected]

    • az2451's avatar
      az2451
      Resolver I

      Thank you very much.

      yes it makes more sense to create 1 static object and change it for each event.