EDIT: forgot the jsfiddle
I've got an SVG image consisting of many paths/shapes, each contained in a <g>
element with an id
. To keep things simple, I've limited my example to two shapes.
I've also got a series of <div>
s - representing several colors - which have a data-attribute
that can match an SVG shape <g>
id. So:
<svg width="428" height="230" xmlns="http://www.w3.org/2000/svg">
<g id="square">
<rect height="91" width="91" y="68.5" x="82.5"/>
</g>
<g id="circle">
<ellipse ry="48" rx="48" id="svg_2" cy="111.5" cx="295.5"/>
</g>
</svg>
<div class="colors" data-square="5" data-circle="0">Red</div>
<div class="colors" data-square="1" data-circle="3">Blue</div>
<div class="colors" data-square="0" data-circle="9">Green</div>
On clicking a .color
<div>
, I'd like to:
Store all the attributes (keys and values) in an object (done),
Filter out any attributes less than 1 (the part I can't figure out)
Then add a class (.active
) to any svg <g>
elements with an id
that matches the attribute key (done, without the filtering).
Here's my jQuery, along with my commented-out attempt to filter the data()
object:
var shapes = $('svg g');
$('.colors').click(function () {
//remove active class from all shapes
$(shapes).attr("class", "");
//store data attributes
var colortotals = $(this).data();
//filter attributes greater than 0
//var colortotals = $(this).data().filter(function() {
//return $(this) > "0";
//});
//add active class to any shape with id matching an attribute key
$.each(colortotals, function(key, value) {
alert(key + ": " + value);
$(shapes).filter('#' + key).attr("class", "active");
});
});
Is this what you are looking for?
$.each(colortotals, function(key, value) {
if (Number(value) > 0) {
$(shapes).filter('#' + key).attr("class", "active");
}
});
Sorry if I didn't understand the question correctly