I'm working on a data visualization proyect, using javascript and d3. In this proyect I'm showing the data using various charts (the data comes from an external source). I'm new in this language so I´m using pieces of code from differents parts of the internet and a lot of the work comes from editing those pieces in order to make them compatible with each other.
I have succefully deploy the charts (A big accomplishment for me, since I started with javascript and HTML just one week ago). Now i want to be able to open a modal when clicking the bars of the charts or, at least, on the labels, but I'm having some trouble with that.
This is how the bars on the chart are defined:
var vakken = svg.selectAll(".question")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(0," + y(d.Question) + ")"; });
var bars = vakken.selectAll("rect")
.data(function(d) { return d.boxes; })
.enter().append("g").attr("class", "subbar");
bars.append("rect")
.attr("height", 16)
.attr("x", function(d) { return (x(d.x0)); })
.attr("width", function(d) { return (x(d.x1) - x(d.x0)); })
.style("fill", function(d) { return color(d.name); });
Any comment on how to achieve this will be appreciated (And feel free to mock me, i kind of deserve it)
You define your bars of your chart as 'rect' dom elements (line with 'bars.append(...)'). As each dom element, you can access it via JavaScript. To access the bars, you have to add an id or class, e.g.:
Then you access it and add your onclick event:
Or with pure JS:
I hope it helps...
Edit: I've forgot your question how to open a modal dialog. There are several ways to achieve to open a modal dialog. The easiest way is to use a library like materializecss or something similar. However, there is a lot of stuff that will be applied to your project.
Here is a simple example, how you can achieve it with jQuery since jQuery keeps the functions simple for the moment.
At first, you have to add a div element which you place in the center of the screen. This div element is hidden by default:
The z-index is used to guarantee that you modal dialog is in the front of your page.
To avoid the clicking on other elements, we use a further div that uses the whole screen:
This
box
is also hidden by default. When you click the bar, then you show both divs, e.g.:If you click on the box, the modal will be closed (as an example):
I think, you find out the further steps ;)