Reputation: 6562
I'd like to be able to both zoom and mouseover an element. Included is an example followed by more details about the scenario.
https://jsfiddle.net/pkerpedjiev/ny5ob3h2/4/
var svg = d3.select('svg')
var zoom = d3.behavior.zoom()
.on('zoom', draw)
svg.append('rect')
.attr('x', 0)
.attr('y', 0)
.attr('width', 400)
.attr('height', 400)
.attr('fill', 'transparent')
.call(zoom)
var xScale = d3.scale.linear()
.domain([0, 10])
.range([0,10])
zoom.x(xScale)
svg.append('text')
.attr('x', 50)
.attr('y', 100)
.text('Hi there')
.attr('visibility', 'hidden')
svg.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 10)
//.attr('pointer-events', 'none')
.on('mouseover', function(d) {
svg.selectAll('text')
.attr('visibility', 'visible');
})
.on('mouseout', function(d) {
svg.selectAll('text')
.attr('visibility', 'hidden')
});
function draw() {
d3.selectAll('circle')
.attr('r', xScale(10));
}
The example just contains a circle and some text. The text is invisible unless the mouse is over the circle. If I scroll using the mouse wheel, the circle changes in size in response to the zoom behavior. If, however, the mouse is over the circle, zooming doesn't work.
Is there a way to fix this? Setting pointer-events
to none
on the circle fixes the zooming, but then the mouseover
event doesn't get called.
Is there way to have both the circle's mouseover
get called and be able to zoom while the mouse is over the circle?
Upvotes: 0
Views: 1618
Reputation: 32327
Yes this is possible by giving the zoom on the circle also.
svg.append('circle')
.attr('cx', 50)
.attr('cy', 50)
.attr('r', 10)
.call(zoom)//giving on circle also
//.attr('pointer-events', 'none')
.on('mouseover', function(d) {
svg.selectAll('text')
.attr('visibility', 'visible');
})
.on('mouseout', function(d) {
svg.selectAll('text')
.attr('visibility', 'hidden')
});
working example here
Hope this helps!
EDIT
If you have lot of elements and you don't like to attach the zoom listener to all the elements then you can attach the zoom to the main group which holds everything.
Like this:
var svg = d3.select('svg').attr("x",500).attr("y",500).append("g")
Attach zoom listener to the group.
svg.call(zoom);
Working code here
Upvotes: 3