Search code examples
jqueryjquery-selectorsclickraphaeldom-selection

Show certain Raphael shapes on click


There is a good answer on how to call Raphael methods on jQuery objects. It works perfectly. But I need a bit more functionality. I want to show shapes width certain attributes on a button click. In that answer, I could only affect all shapes in the array. How can I filter them? I used that piece of the code:

$("button").click(function() {
    $.each(cottages_array, function(i, c){
        c.animate({fill: '#55bfe1', opacity: 1}, speed_anim_in);
    });
});

I have attribute type for my shapes and I want to highlight shapes only with a certain type (type A for example). Inside the cycle, I can fill different types with different colors, but I don't know how to apply any conditions to the click outside of the cycle using jQuery.

for (var j = 0; j < obj.cottages.length; j++) {
    var obj_cottages = obj.cottages[j],
    my_path = canvas.path(obj_cottages.coords);
        my_path
            .attr({stroke: "none", fill: cottage_color_start, "fill-opacity": 0.8, opacity: 0, cursor: "pointer"})
            .data('type', obj_cottages.type)

if (obj_cottages.type == 'A') {
    my_path
        .attr({stroke: "none", fill: "#fff", "fill-opacity": 0.8, opacity: 0, cursor: "pointer"})
}

I've spent the whole day trying to figure out how to do it and I have no luck at all.

http://jsfiddle.net/Fionaa/5BYK6/


Solution

  • The first thing I did was to add an id to your buttons, as we need to know which type we want:

    <button id="A">Type А</button>
    <button id="B">Type B</button>
    <button id="C">Type C</button>
    

    Next I find the id of the button clicked:

    // get id of button which was clicked
    var type = this.id;
    

    Then I create a temporary set to hold the cottages which are of that type:

    // create temporary set
    var set = canvas.set();
    

    Then in your loop, I find the cottage type that is equal to the clicked type, and add to temporary set

    // loop all cottages and find the type we want
        c.forEach(function(el){
    
            // put cottages in the temp set
            if(el.data("type") == type){
                set.push(el);
            }
    
        });
    

    And finally animate this temporary set

    // animate this set
        set.animate({fill: '#55bfe1', opacity: 1}, speed_anim_in);
    

    I have a fiddle for you - http://jsfiddle.net/5BYK6/1/

    EDIT

    Ok I have added the following:

    // fade any previous set
        if(prevSet) {
            prevSet.animate({opacity: 0}, speed_anim_out);
        }
    
    // store current set to remove later
        prevSet = set;
    

    Basically we store the previous set we created, and check if there is one that exists in prevSet, we animate to opacity: 0, using your speed_anim_out variable.

    See updated fiddle for this http://jsfiddle.net/5BYK6/2/