how to select parent div of svg in D3.js - javascript

I have read several articles and tutorials but couldn't find a sufficient answer on how to select the parent div of the svg using d3.select. I basically just want to append a tooltip to the div which contains my chart like this.
//this selection probably doesn't make sense...
var tooltip = d3.select("#pie-svg").select(this.parentNode).append("div")
.attr("class", "piechart-tooltip")
.style("opacity", 0);

Along the lines of this question:
var tooltip;
d3.select("#pie-svg").each(function() {
tooltip = d3.select(this.parentNode).append("div")
.attr("class", "piechart-tooltip")
.style("opacity", 0);
});
The problem with the code you've posted in the question is that this won't be defined (or set to the right element) in this context. When used with .each(), it will.

Related

How to add controls and buttons to map?

This is probably a really basic question, but I can't figure it out. I'm building a map using D3. My code creates and svg, appends a g element to it and then draws the map within it. What I want is to render a set of buttons and controls that are positioned inside the map viewer. They would be zoom buttons, a dropdown to display different sets of data and a timeline slider.
For example, with the dropdown selector I want placed I did this:
I tried using d3 as in:
svg.append("select")
.attr("class", "field_dropdown")
.data(['housing_unit', 'tenure', 'median_contract_rent', 'median_value', 'median_income'])
.enter()
.append("option")
.attr("value", function(d) {
return d
});
but this rendered the select item and option items separate from each other, and not even visible within the map container.
As mentioned, not only do I wanna add a dropdown, but also buttons for zoom and a slider, among other items. How do I render and position them in the map container?
Thanks
This has been asked several times (surely a duplicate): you cannot append HTML elements ("div", "p", "select", "h1" etc) to an SVG. It will simply not work.
The best solution, in your case, is creating the drop down menu and the other controls outside the SVG, in the HTML.
But, if you really want to create this drop down inside the SVG (which I don't advise), you can use foreignObject (which will not work on IE):
var foreign = svg.append("foreignObject")
.attr("width", 100)
.attr("height", 100)
.append("xhtml:body");
var select = foreign.append('select')
.attr("class", "field_dropdown")
//the rest of your code

Iterating throug SVG elements with D3.js

What I'm trying to do is relatively simple but I'm new to JS and D3.js.
I have created a bunch of rectangles using SVG through D3.js.
I added some code to handle a click event and in there I'd like to iterate through all drawn nodes and do something with them as long as a specific property matches the same property in the one that's been clicked.
Here's the code that draws the rectangles (only one of them here);
d3.select("svg")
.append("rect").attr("x", 50)
.attr("y", 10)
.attr("height", 20)
.attr("width", 200)
.attr("title", "catalog")
.style("fill", "#CB4B19")
.on("click", mouseClick)
And here's how I'm trying to retrieve the "title" property of each rectangle drawn and compare it to the clicked one (and in this case, just log it in the console). I know this is probably basic but I can't figure out what I'm doing wrong here.
function mouseClick(d) {
var t = d3.select(this).attr("title"); //store the "title" property of the clicked rectangle
d3.selectAll("rect").each(function(d, i){ //Select all rectangles drawn
if(d3.select(this).attr("title") == t){ //for each one, if the "title" property = the one initially chosen
console.log(t); //do something here
}
})
}
Your code actually seems to be working correctly. At least for me it did. One thing I will say is that d3 does mimic jQuery syntax in that it lets you select elements with attributes with the d3.select('element[attributeName="?"]') syntax. You can read more about selections here.
So for your example, you could do
var t = d3.select(this).attr("title");
// select all rectangles with the attribute title
d3.selectAll("rect[title='" + t + "']").each(function(d, i){
console.log(t);
});
You no longer need the if statement to check because you are only selecting them. I made a simple jsFiddle to show this. I made 3 different types of rectangles with different title attributes and when you click on them, it only selects rect that have the same title attribute.
http://jsfiddle.net/augburto/znqe8nqr/

Getting .attr("display":none) to work on mouseout (D3.js)

I am making an interactive D3.js visualization with popup/tooltips to the data points so that on a mouseover event, a popup will appear next to the selected point with some information
Currently I have achieved this with the code below - the tooltip appears on mouseover. When the user moves the mouse to another point, the original tooltip disappears and the correct tooltip appears next to the new data point.
However, the mouseout event is not functioning as it should - the tooltip is not disappearing once the mouse leaves the datapoint. If the user does not move the mouse over a new data point, for example, the old tooltip remains there.
Relevant bits of code:
svg.selectAll("path")
//other stuff here
.on("mouseover", function(d) {
div.transition()
.duration(200) //mouseover transition does not seem to work, but that's minor
.style("opacity", .8);
div .html(d.datetime.substring(0,10) )
.style("left", (d3.event.pageX + 5) + "px")
.style("top", (d3.event.pageY - 24) + "px")
.attr("display", display);
})
.on("mouseout", function(d) {
div.attr("display", none);
})
//bit of code where I append the tooltip to the right element
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", .8);
});
What am I doing wrong?
Thanks!
none is a string. So you have to enclose it in quotes. Also note that display is a css style attribute. So it should be applied as shown below.
div.style("display","none");
Other alternative options for implementing the same are the following.
Option 2:
div.attr("hidden",true);//to hide
div.attr("hidden",null);//to show
Option 3:
div.style("opacity",0);//to hide
div.style("opacity",1);//to show
Here is a working code snippet.
var button = d3.select("body")
.append("button")
.text("Mouse Over Me");
button.on("mouseover",function(){
div.style("display","block");
});
button.on("mouseout",function(){
div.style("display","none");
});
var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("display", "none")
.text("Hello This is a sample");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
display is not an HTML attribute, this is CSS. You need to change your code to something like this if you want to hide the element:
div.css({ "display": "none" });
Or just use the jQuery shortcut: div.hide();.
I would like to use hide() or show(). change from
div.attr("display", display);
to
div.hide();
here is the comments from .hide() or display: none? jQuery
"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline."
This looks like you are following the tutorial here, right down to the extra space before the .html in the mouseover event. (Which is fine...the only reason I recognized that little syntax is because I spent all day staring at it!)
http://www.d3noob.org/2013/01/adding-tooltips-to-d3js-graph.html
You post the relevant code above, but are you also selecting the div that you want to operate on using the select method? This may be why your transition isn't working the way you want it to.
eg:
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
otherwise or in addition the proper way to get the tooltip to go away is as Gilsha answered above with this line on mouseout:
div.style("display","none");

Reorder elements of SVG ( z-index ) in D3.js

I realise this question has been asked before but I can't get to the bottom of it.
Here is my chart... http://www.gogeye.com/financialnews/piechart/index3.html
All I want to do is have the coin render behind the graph. I know D3 renders in order they are appended.
I have tried to re-append the coin but can't seem to get it working.
I've tried reordering when things are appended in the DOM but keep getting errors probably because variables are getting called before being defined etc.
Can someone give me an example of how to fix this with my code? I don't want you to do the work for me but I've been pulling my hair out for so long, I can't seem to apply other peoples examples to mine.
thanks
I would recommend creating some "layers" using svg g elements which stands for "group".
When you render your chart, you can first define your layers:
var layer1 = svg.append('g');
var layer2 = svg.append('g');
var layer3 = svg.append('g');
// etc... for however many layers you need
Then when you append new elements, you can decide which layer you want them to be on, and it won't matter what order you assign them in, because the group elements have already been added to the DOM, and are ordered. For example:
var layer1 = svg.append('g');
var layer2 = svg.append('g');
var redCircle = layer2.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 16)
.attr('fill', 'red')
var blueSquare = layer1.append('rect')
.attr('x', 25)
.attr('y', 25)
.attr('width', 50)
.attr('height', 50)
.attr('fill', 'blue');
In this case the red circle will be visible above the blue square even though the blue square was created last. This is because the circle and the square are children of different group elements, which are in a pre-defined order.
Here's a FIDDLE of the above example so you can see it in action.
Doing this should take a lot of the guesswork out of when to add certain elements to your chart, and it also helps to organize your elements into a more logical arrangement. Hope that helps, and good luck.
I am using the D3.js, and found that it has a built-in function for changing the z-order of SVG elements programmatically after the original drawing.
RipTutorial: svg--the-drawing-order covers the d3 builtin function
Quotes from this link:
selection.raise(): Re-inserts each selected element, in order, as the last child of its parent. selection.lower(): Re-inserts each selected element, in order, as the first child of its parent.
d3.selectAll("circle").on("mouseenter", function(){
d3.select(this).raise();
});
d3.selectAll("circle").on("mouseleave", function(){
d3.select(this).lower();
});
see live example their jsFiddle

Implementing <div> tooltips via d3 within an <svg> container

I'm relatively new to D3, svg, and javascript in general, so please bear with me :]
I have been experimenting with D3 for creating plots and graphs. I have created a small plot using D3 and have been attempting to make it compatible with IE8. Here is a link to the more-or-less working build of my graph.
http://jsfiddle.net/kingernest/YDQR4/1/
After some research, I quickly realized that the only way running D3 on IE8 would be at all feasible is by using other APIs in conjunction with D3. Luckily, I found that someone had already put in some work into a project called "r2d3" which, from my understanding, uses raphael to paint the canvas on the IE8 window instead of using SVG (which apparenly was not supported in IE8).
I have been able to get items drawn on the screen, which is half the battle. However, I'm having many issues, particularly with my tooltip. My tooltip is written as a DIV container that floats and changes position/opacity on hover of the data circles. This seems to work fine in other browsers, but with r2d3, I have not been able to get it working. I suspect this is because of the fact that I am creating the div tooltip outside of the (in the #main div). However, I have tried placing tooltips inside of the SVG container with no avail. I then did more reseach and discovered I would have to wrap a div container inside a tag, but after some experimentation with this, I still wasn't able to get the tooltip to work correctly in IE. I attempted to wrap the in a SVG group (), and altered the positioning of this object instead, but this did not seem to work either, and simply through numerous exceptions when trying to append the foreignObject tag to a group.
At this point I'm sort of stuck, and was wondering if anyone had any suggestions as to how I may be able to successfully implement the tooltips. I've also noticed that using d3.select(this) inside my functions, when attempting to select a particular data point (in this case, a circle) seems to present a number of issues when attempting to access or modify that item's attributes, but I think this is a whole other issue entirely.
Any help is greatly appreciated!
Example of how I'm currently creating the tooltips:
//Create tooltip element
var tooltip = d3.select("#main")
.append("div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("z-index", "10")
.style("opacity", 0);
function mousemove()
{ //Move tooltip to mouse location
return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+10)+"px");
}
//Mouseover function for circles, displays shortened tooltip and causes other circles to become opaque
function mouseover()
{
var myCircle = d3.select(this);
d3.select(this).attr("class", "dataCircleSelected"); //Color circle green
tooltip.html( //Populate tooltip text
"Username: " + d3.select(this).attr("username") + "<br/>" +
"Session ID: " + d3.select(this).attr("sessionid") + "<br/>" +
"Impact CPU: " + d3.select(this).attr("impact")
)
.transition()
.duration(250)
.style("opacity", .7);
//After 1000ms, make other circle opaque
svg.selectAll("circle")
.filter(function(d, i){ //return every other circle
return !d.compare(myCircle[0][0].__data__);
})
.transition().delay(1000)
.style("opacity", .2);
}
Have you tried using foreignObjects AND explicitly using the xhtml namespace for html tags in the foreignObject (write xhtml:div instead of div) as explained here: HTML element inside SVG not displayed ?
This would give something like that for the tooltip definition
var tooltip = d3.select("#main").append("foreignObject")
.append("xhtml:div")
.attr("class", "tooltip")
.style("position", "absolute")
.style("z-index", "10")
.style("opacity", 0);

Categories

Resources