Reputation: 2453
EDIT: Here is a better JSFiddle
The third time I hover over the circle, the rectangle becomes huge and will no longer disappear.
The code to draw the text and rectangle is taken from this post; I need to have the size of the rectangle depend on the size of the text, I can't define it beforehand.
var rsr = Raphael("holder", '1160', '1400');
xpos = 200;
ypos = 200;
rad = 50;
cir = rsr.circle(xpos, ypos, rad);
cir.attr({
fill: '#444',
'fill-opacity': 1,
stroke: 'none'
});
cir.hover(function() {
this.animate({ r: rad*1.2 }, 200);
var recttext = rsr.set();
el = rsr.rect(0, 0, 0, 0, 3);
el.attr({fill: '#fff'});
txt = rsr.text(4,10, "Title text").attr({"text-anchor":"start",fill:'#000000',"font- size": 12});
recttext.push(el);
recttext.push(txt);
var att = {width:recttext.getBBox().width, height:recttext.getBBox().height};
el.attr(att);
recttext.translate(xpos - recttext.getBBox().width/2, ypos - rad - 20);
}, function() {
this.animate({ r: rad }, 100);
recttext.remove();
el.remove();
txt.remove();
});
Sorry for the code spacing, it got mangled after a few copy/pastes.
Upvotes: 0
Views: 127
Reputation: 11258
You have error in your code. The second function returns error message:
Uncaught ReferenceError: recttext is not defined
because variable recttext
is not visible in the second function. Similar could happen with variables el
and txt
. You did not use var el = ...
in the first function so it was defined in global space and seen in the second without problem.
You have to move definition of recttext
out of hover functions (and add variables el
and txt
):
var recttext, el, txt;
cir.hover(function() {
this.animate({ r: rad*1.2 }, 200);
recttext = rsr.set();
...
In JavaScript, if variable is used for the first time without var
it is placed in global space. That's why variables el
and txt
were seen everywhere. Variable recttext
was defined with var
so it was scoped to the first function. Placing them out of hover functions we set them all as global.
Example in jsfiddle still shows flickering. Version used is 2.1.0. With version 2.1.2 there is no flickering. The latest Raphael library is 2.1.2: Milestone for bug fixes from contributors pull requests.
Upvotes: 1