nykon
nykon

Reputation: 625

Style a d3 element with jQuery and CSS

I have somehow a technical question. I would like to know if there is a possibility to style a d3 element with jQuery.

For instance a "Collatz Graph" example from the d3 site http://www.jasondavies.com/collatz-graph/ is producing a circle - like nodes with small labels.

In that case the numbers 1, 2, 3 and so on. The number is nothing more than a piece of code e.g.

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

How could I style this element with jQuery? e.g. adding a red border by clicking it?

Obviously I would need a class or id in the <text ... > and proceed as follows:

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

In my code, both d3 is working (I can see a graph) and jQuery is working (I can for instance style or do something else with the regular HTML elements). BUT when I try style d3 element I get no result.

I will be very grateful for any hint or advice.

Upvotes: 0

Views: 478

Answers (3)

altocumulus
altocumulus

Reputation: 21578

To cut a long answer short: Don't do it! Try searching for [svg][jquery] namespace on SO for a variety of problems you might run into when trying to use jQuery to manipulate svg. Although there are ways around it, most of them involve a lot of tweaking and doing stuff in pure JavaScript with no jQuery involved.

jQuery was designed to handle html which results in difficulties dealing with other namespaces like svg. There are some bug reports on jQuery's bug tracker but the jQuery foundation has closed all of them and at the time of writing lists these issues on its Won't Fix page. There is also a good answer to another question on SO which has just recently been awarded a bounty giving a more detailed insight into the technical problems involved.

I have myself combined both jQuery and D3 but separated their use based on the purpose they were designed for: jQuery for HTML manipulation and D3 for dealing with svgs.

Upvotes: 1

scniro
scniro

Reputation: 16989

Yes you can, however when targeting <svg> elements, you must chose style properties such as stroke and fill. For example, in that site, if you open up your dev tools and paste/execute the following, you'll see the changes

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

Edit

Per discussion you can attach event handlers on your <g> elements with jQuery and do whatever else you wish

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

Upvotes: 1

BDD
BDD

Reputation: 715

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 could also do .classed or .style

Upvotes: 0

Related Questions