Reputation: 194
Earlier today I got some simple code to work allowing an image to slide over on mouse over, and decided to try to turn that into a class so I could instantiate it. However, I'm running into some problems.
init() is called on window load, which sets up shifttabout() as a function to be called upon mousing over the image. However, when shifttabout() is called, I get the following error: "this.movetabout is not a function." How can this be?
<script type="text/javascript">
function SlidingTab(img)
{
this.self = this;
this.outtimer;
this.intimer;
this.left = 0;
this.interval = 20;
this.animatingout = false;
this.animatingin = false;
this.increment = 10;
this.extenddist = 100;
this.imgobj = img;
this.movetabout = function(){
alert("moveout");
this.animatingout = true;
this.left = parseInt(this.imgobj.style.left);
if(this.left != this.extenddist)
{
this.imgobj.style.left = this.left + this.increment + 'px';
this.self = this;
this.outtimer = setTimeout(this.self.movetabout, this.interval);
}
else
{
this.animatingout = false;
}
};
this.shifttabout = function(){
alert("shiftout");
if(this.animatingin)
{
this.animatingin = false;
clearTimeout(this.intimer);
}
if(!this.animatingout)
{
this.movetabout();
}
}
this.init = function(){
this.imgobj.style.position = 'relative';
this.imgobj.style.left = '0px';
this.self = this;
this.imgobj.onmouseover=this.self.shifttabout;
}
}
function init(){
var img1 = document.getElementById("tab1");
var tab1 = new SlidingTab(img1);
tab1.init();
}
window.onload = init;
</script>
Presumably I am setting up the onmouseover function incorrectly somehow, since all class variables appear to be undefined or otherwise messed up in shifttabout() when it is called by mouse hover, but not when it is called directly via init().
Upvotes: 0
Views: 82
Reputation: 4820
your problem looks to be caused by these lines. Youre on the right track, in that you need to be properly setting the context of your function.
this.self = this;
this.imgobj.onmouseover=this.self.shifttabout;
change it to the following should properly set the context
this.imgobj.onmouseover=this.shifttabout.bind(this);
#bind(this)
sets the scope of this
inside the function to the input you pass it (in this case its the current scope)
Upvotes: 2
Reputation: 3967
The this
you're using in the shifttabout
refers to the shifttabout
this
- not the SlidingTab
this
.
You should pass the vars needed from outside shifttabout
into it to use them properly.
Hope that helps.
Upvotes: 0