I’m trying to create an easy play / pause button system with Raphael but I keep getting scope issues.
The buttons themselves are just images embed in the SVG tag thanks to Raphael.
The goal is to have this "event cycle" :
- If play.png is displayed,
onmouseoverremove()play.png and show play-hover.png - If play-hover.png is displayed,
onclickremove()play-hover.png show pause.png - If pause.png is displayed,
onmouseoverremove()pause.png show pause-hover.png - If pause-hover.png is displayed,
onclickremove()pause-hover.png show play.png
It seems really stupid but I really have problems with scope and closures. This is the code I have at the moment :
function toPlay(pauseHover) {
pauseHover.remove();
var play = paper.image("images/play.png", Img.X, Img.Y, Img.height, Img.width);
play.node.onmouseover = toPlayHover(play);
}
function toPause(playHover) {
playHover.remove();
var pause = paper.image("images/pause.png", Img.X, Img.Y, Img.height, Img.width);
pause.node.onmouseover = toPauseHover(pause);
}
function toPlayHover(play) {
play.remove();
var playHover = paper.image("images/play-hover.png", Img.X, Img.Y, Img.height, Img.width);
playHover.node.onclick = toPause(playHover);
}
function toPauseHover(pause) {
pause.remove();
var pauseHover = paper.image("images/pause-hover.png", Img.X, Img.Y, Img.height, Img.width);
pauseHover.node.onclick = toPlay(pauseHover);
}
var play = paper.image("images/play.png", Img.X, Img.Y, Img.height, Img.width);
toPlayHover(play);
I don’t know exactly why this doesn’t work since firebug isn’t giving me any errors in the console, but I think it’s because the toPlayHover() function can’t be called within the toPlay() function.
It’s because you are immediately calling each function instead of registering it as a callback. To fix, wrap each callback in an anonymous function like so: