Styling a d3 element with jQuery and CSS

I have a kind of technical question. I would like to know if it is possible to style the d3 element using jQuery.

For example, the "Collatz Graph " example from d3 http://www.jasondavies.com/collatz-graph/ creates circle-like nodes with small labels.

In this case, the numbers 1, 2, 3, etc. The number is nothing more than a piece of code, for example.

 <text dy=".31em" text-anchor="start" transform="rotate(90)translate(8)">32</text>

      

How can I style this element using jQuery? for example adding a red border by clicking on it?

Obviously I need a class or id in <text ... >

and proceed like this:

 $(".nome_class").click(function() {
    $(this).css( "border", "3px solid red" );
 }); 

      

Both d3 works in my code (I can see the graph) and jQuery works (I can for example style or do something with regular HTML elements). BUT when I try to create a d3 style element I get no result.

Any hint or advice would be very grateful.

0


source to share


3 answers


To cut the long answer short: Don't do it! Try searching for the [svg] [jquery] namespace on SO for a lot of problems you might run into when trying to use jQuery to control svg. While there are ways around, most involve a lot of customization and reading everything in pure JavaScript without jQuery involved.

jQuery was designed to handle html, which leads to the difficulties associated with other namespaces like svg. There are some bug reports in the jQuery bug tracker, but the jQuery Foundation has closed all of them and at the time of writing the lists, these problems will not be fixed . There is also a good answer to another question on SO that recently won an award giving more insight into technical issues.



I myself combined both jQuery and D3, but separated their use based on the purpose they were intended for: jQuery for processing HTML and D3 for working with svgs.

+1


source


Yes you can, however, when targeting elements, <svg>

you must choose style properties such as and . For example, on this site, if you open your developer tools and paste / execute the following, you will see the changes stroke

fill

$('circle').css('stroke', 'green')
$('circle').css('fill', 'red')

      

Edit



During the discussion, you can attach event handlers to your elements <g>

using jQuery and do whatever you want.

$('g').click(function(e) {
    console.log($(this).children().closest('text').text());
    // do whatever else  
});

      

+1


source


Why don't you just use d3 to style the element?

d3.select(".nome_class").on('click', function(){
    d3.select(this).attr("style", "border: 3px solid red;")
})

      

You can also do .classed

or.style

0


source







All Articles