I am using this code to change the fill colour of an SVG object and it works:
$(function() {
$('g').mouseenter(function () {
$('path, rect, circle', this).attr('fill', '#00C8C8');
})
});
But, I only want to change the fill colour if the existing fill colour is of a certain value. So, I thought something like this:
$(function() {
$('g').mouseenter(function () {
if($('circle', this).attr('fill') == '#DCDCFF'){
$('circle', this).attr('fill', '#00C8C8');
}
})
});
EDIT: ...again, slight error in the jsfiddle (thanks Robert)
I've created a page on jsfiddle here: http://jsfiddle.net/Wc9ZE/4/
to show what I'm trying to get at, I've also made the colours more distinct.
The problem is, all the rectangles turn yellow then red, I only want the large one that was originally yellow to turn red then back to yellow. The little white rectangle should remain white.
Your brackets are in the wrong place
if($('path, rect, circle', this).attr('fill') == '#DCDCFF') {
And the jsfiddle seems rather strange as in the first circle case you're using val rather than attr i.e.
if ($('circle', this).val('fill')
should be
if ($('circle', this).attr('fill')
shouldn't it?
And finally if you only want it to work on one rect then you should give that rect an id attribute (below I've assumed id="r") and then change the code like this...
$(function () {
$('g').mouseenter(function () {
if ($('circle', this).attr('fill') == 'yellow') {
$('circle', this).attr('fill', 'pink');
}
if ($('#r', this).attr('fill') == 'red') {
$('#r', this).attr('fill', 'yellow');
}
}).mouseleave(function () {
if ($('#r', this).attr('fill') == 'yellow') {
$('#r', this).attr('fill', 'red');
}
if ($('circle', this).attr('fill') == 'pink') {
$('circle', this).attr('fill', 'yellow');
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With