0

So I have this code:

function theObject(){
    this.someelement = $("#someelement");
    this.someotherelement = $("someotherelement");
    this.someelement.fadeOut(500, function(){
       this.someotherelement.attr("title", "something");
       this.someelement.fadeIn(500); 
    });
}

for some reason this.someotherelement is undefined. I'm guessing because it's wrapped in a function(){}?

3
  • Is that the id of the element? You are missing a # sign. Commented Jul 22, 2010 at 17:25
  • post some of the relevant html too, so it will be more clear... Commented Jul 22, 2010 at 17:26
  • 1
    Inside the function, this refers to this.someelement (actually to its DOM element). With most (every?) jQuery function that takes a callback, this refers to the (DOM) element you call the function on. Commented Jul 22, 2010 at 17:29

4 Answers 4

3

Inside the function this means something else. You could capture it though:

this.someotherelement = $("someotherelement");
var _this = this;
this.someelement.fadeOut(500, function(){
   _this.someotherelement.attr("title", "something");
   _this.someelement.fadeIn(500); 
});
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of _this.someelement you could also use $(this).
1

This is caused by a JavaScript scoping issue. Creating a function creates a new scope for this which makes this refer to the function. You can fix it by doing ... this:

function theObject(){
  this.someelement = $("#someelement");
  this.someotherelement = $("someotherelement");

  // bind this to that (what?). This way, this will still be accessible inside
  // the new function's scope as that
  var that = this;
  this.someelement.fadeOut(500, function(){
    that.someotherelement.attr("title", "something");
    that.someelement.fadeIn(500); 
  });
}

Comments

0

I have edited your code , I hope it helps.

function theObject(){
    var someelement = $("#someelement");
    var someotherelement = $("#someotherelement");
    someelement.fadeOut(500, function(){
       someotherelement.attr("title", "something");
       someelement.fadeIn(500); 
    });
}

Comments

0

is someotherelement an ID? If so, you are missing a #...

this.someotherelement = $("#someotherelement");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.