Search code examples
javascriptjqueryraphaeldonut-chart

Raphaël Donut chart click and unclick sections


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/


Solution

  • 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");