Reputation: 1
I have small problem with a submit button.. When it's clicked I want it to perform different actions, but two later than the other one. I have been trying to use a setTimeout from Javascript and place some of the actions I want it to perform in a different function, but then my code doesn't work anymore because it doesn't know what 'this' is anymore. Any help please?
function test(){
$(this).addClass("voted");
$(this).val('lighted up');
}
$(".stem").click(function() {
$(this).parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(test,1500);
});
Upvotes: 0
Views: 5566
Reputation: 62488
$(this)
will be undefined
in function test as $(this) refers to the current element whose event has occurred and your function is separate thing, use a variable to store reference of it.
do like this:
var temp;
$(".stem").click(function() {
temp = $(this);
$(this).parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(test,1500);
});
function test(){
temp.addClass("voted");
temp.val('lighted up');
}
Upvotes: 1
Reputation: 700362
You can use the proxy
method to specify what this
shold be for the function call:
setTimeout($.proxy(test, this),1500);
Upvotes: 0
Reputation: 679
You need to store a variable holding the value of this
:
function test($el){
$el.addClass("voted");
$el.val('lighted up');
}
$(".stem").click(function() {
var $el = $(this);
$el.parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(function() {
test($el);
}, 1500);
});
Upvotes: 0
Reputation: 63524
Store a reference to this
in _this
and pass that as a parameter to temp
.
function test(el) {
$(el).addClass("voted");
$(el).val('lighted up');
}
$(".stem").click(function() {
var _this = this;
$(this).parent().parent().parent().find(".red").addClass("filltherm");
setTimeout(function () {
test(_this);
}), 1500);
});
Upvotes: 1