Raphaël Donut chart click and unclick sections

243 Views Asked by At

I am a novice with this but I am trying to create a donut chart that has sections that scale larger when clicked and then when a different section is clicked the first section returns to the original size and the new section scales larger.

I have the chart and the scaling with the click but right now I can only get the section to go back to the original size with mouseout.

This is the code I have:

 p.click(function () {
            p.stop().animate({transform: "s1.1 1.1 " + cx + " " + cy}, ms, "elastic");
            txt.stop().animate({opacity: 1}, ms, "elastic");
        }).mouseout(function () {
            p.stop().animate({transform: ""}, ms, "elastic");
            txt.stop().animate({opacity: 0}, ms);
        });

Fiddle: http://jsfiddle.net/dll416/70twey1o/1/

2

There are 2 best solutions below

4
On BEST ANSWER

The important thing is to be able to select all of the other sectors and text labels from within the click listener function.

I've created an example which achieves what you're looking for by assigning a class to each sector and text label, and uses these classes to perform the "hide" animations: http://jsfiddle.net/8opkfpxs/4/

Setting up the classes:

p.node.setAttribute('class', 'sector');
txt.node.setAttribute('class', 'sectorTxt');

Accessing the classes when a sector is clicked:

        p.click(function (e) {
            donut.forEach(function(element) {
                var className = element.node.getAttribute('class');
                if(className === 'sector') {
                    element.stop().animate({transform: ""}, ms, "elastic");   
                }
                else if(className === 'sectorTxt') {
                    element.stop().animate({opacity: 0}, ms);   
                }
            });
            p.stop().animate({transform: "s1.1 1.1 " + cx + " " + cy}, ms, "elastic");
            txt.stop().animate({opacity: 1}, ms, "elastic");                    
        });

You'll also need to store the Raphael context in a variable - donut in the example above - to be able to use the forEach function within the click listener.

donut = Raphael("holder", 700, 700).donutChart(350, 350, 200, 50, values, labels, "#fff");
3
On

Remove the mouseOut function and before appling the transform onClick reset the whole set transformations and attribute changes, also separate the chart set into 2. I also recommend you draw each chart inside an array.

I just changed these lines:

chartTxt = this.set(),
chart = this.set();

and

p.click(function () {
    chart.transform("");
    chartTxt.attr({opacity: 0});
    this.stop().animate({transform: "s1.1 1.1 " + cx + " " + cy}, ms, "elastic");
    txt.stop().animate({opacity: 1}, ms, "elastic");
});

and

chart.push(p);
chartTxt.push(txt);

http://jsfiddle.net/crockz/m4tcr4tg/