Anh Tuan Nguyen
Anh Tuan Nguyen

Reputation: 979

d3 svg differentiate onclick

I'm using d3 to add an onClick() event to my svg container.

   var svg = d3.select("svg").on("click", ()=>{console.log("svg");});

I also have an onclick event for an embedded line Object within the svg;

   var line =d3.select("svg").append("line")
               .attr("x1",10)
               .attr("y1",10)
               .attr("x2",100)
               .attr("y2",100)
               .attr("stroke-width",6)
               .attr("stroke","black")
               .on("click" ()=>{console.log("line");})

I want both events to be separate in the sense, that whenever I click on the line I only get the output "line" instead of "line" and "svg". How can I do that?

Upvotes: 0

Views: 339

Answers (2)

Anh Tuan Nguyen
Anh Tuan Nguyen

Reputation: 979

I have to check on th svg if there any prevented events

var svg = d3.select("svg").on("click", ()=>{
                                if(d3.event.defaultPrevented)
                                console.log("svg");});

On the line object then I can use preventDefault()

var line =d3.select("svg").append("line")
           .attr("x1",10)
           .attr("y1",10)
           .attr("x2",100)
           .attr("y2",100)
           .attr("stroke-width",6)
           .attr("stroke","black")
           .on("click" ()=>{
                     d3.event.preventDefault();
                     console.log("line");})

Upvotes: 1

eko
eko

Reputation: 40677

You can do that by using the preventDefault function:

.on("click" ()=>{
    d3.event.preventDefault();
    console.log("line");
})

Upvotes: 1

Related Questions