In this piece of SVG (tried in FF 8, Safari 5.1.2, Chrome 16, all on Mac), when moving mouse over the bar, none of the browsers properly detect each on-mouse-over/out event, sometimes it works sometimes it doesnt. But it's consistent across all the browsers so it's probably something about the SVG code. Using onmouseover
and onmouseout
gives the same result - doesn't work properly.
What would be the correct way of implementing on hover for SVG rect
angles?
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800" height="600" version="1.1" style="display:inline">
<style type="text/css">
.bar {
fill: none;
}
.bar:hover {
fill: red;
}
</style>
<g>
<rect class="bar" x="220" y="80" width="20" height="180" stroke="black" stroke-width="1" />
</g>
</svg>
What's happening is that the mouse events are not detected because the fill is 'none', just add:
.bar {
fill: none;
pointer-events: all;
}
Then it works just fine.
.bar:hover {
fill: red !important;
}
fill: none; pointer-event: all;
should work in most modern browsers, but IE9 and IE10 doesn't support pointer-events
. Besides, you can also set pointer-events: fill
, This fill
value is SVG only, meaning the value of fill
or visibility
doesn't affect pointer events processing.
A workaround for IE9 and IE10 is to set CSS to fill: transparent
if pointer-events
is not supported (you can use Modernizr to detect browser features).
$("#rect").mouseenter(function() {
$(this).css("fill", "teal")
}).mouseout(function(){
$(this).css("fill","transparent")
})
#rect {
fill: transparent;
stroke: blue;
stroke-width: 1px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<svg width=300 height=300>
<rect id="rect" x=0 y=0 width=100 height=100></rect>
</svg>
Try giving it a non-transparent fill.
Also, the <style>
needs to go outside the <svg>
.
Try do it through jQuery :
$(".bar").attr("disable","True");
$(".bar").css("background-color","Red");
$(".bar").mouseenter(function() {
$(this).attr("disable","False");
});
$(".bar").mouseleave(function() {
$(this).attr("disable","True");
});
Or alternatively :
$(".bar").hide();
$(".bar").css("background-color","Red");
$(".bar").mouseenter(function() {
$(this).show();
});
$(".bar").mouseleave(function() {
$(this).hide();
});