Can someone find a problem in the code below
$(document).ready(function () {
$("#leftsettingswindow").on("keyup", "#fontsize2", function () {
setTimeout(function () {
var txtVal = this.value;
$('#content').css("font-size", txtVal + "%");
}, 3000);
});
});
this works flawlessly,
$(document).ready(function () {
$("#leftsettingswindow").on("keyup", "#fontsize2", function () {
var txtVal = this.value;
$('#content').css("font-size", txtVal + "%");
});
});
Any ideas?
asked May 3, 2014 at 5:26
user1967599
-
What is the console error message?doniyor– doniyor2014年05月03日 05:31:27 +00:00Commented May 3, 2014 at 5:31
-
still no resizing happening even after changing this.value; to your suggestionuser1967599– user19675992014年05月03日 05:32:41 +00:00Commented May 3, 2014 at 5:32
-
event.returnValue is deprecated. Please use the standard event.preventDefault() instead. 2 Uncaught TypeError: Cannot read property 'toLowerCase' of undefineduser1967599– user19675992014年05月03日 05:34:40 +00:00Commented May 3, 2014 at 5:34
4 Answers 4
this is not a local variable, so it isn't saved in the closure. You need to bind a local variable to it:
$(document).ready(function () {
$("#leftsettingswindow").on("keyup", "#fontsize2", function () {
var savedThis = this;
setTimeout(function () {
var txtVal = savedThis.value;
$('#content').css("font-size", txtVal + "%");
}, 3000);
});
});
answered May 3, 2014 at 5:33
Barmar
789k57 gold badges555 silver badges669 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
setTimeout does not invoke in the same scope. So this is not the same this as in your 2nd example.
...
var self = this;
setTimeout(function () {
var txtVal = self.value;
$('#content').css("font-size", txtVal + "%");
}, 3000);
...
answered May 3, 2014 at 5:33
nowk
33.2k2 gold badges37 silver badges41 bronze badges
Comments
Credit to Barmar who answered this on another thread.
"this" is not a local variable, so it isn't saved in the closure. You need to bind a local variable to it:
$(document).ready(function () {
$("#leftsettingswindow").on("keyup", "#fontsize2", function () {
var savedThis = this;
setTimeout(function () {
var txtVal = savedThis.value;
$('#content').css("font-size", txtVal + "%");
}, 3000);
});
});
answered May 3, 2014 at 5:42
user1967599
Comments
In code snippet, "this.value" returns "undefined" after 3 secs.
So, use selector, instead of this
$(document).ready(function() {
$("#leftsettingswindow").on("keyup", "#fontsize2", function() {
setTimeout(function() {
var txtVal = $('#fontsize2').val();
$('#content').css("font-size", txtVal + "%");
}, 3000);
});
});
answered May 3, 2014 at 5:47
suneetha
8171 gold badge6 silver badges14 bronze badges
Comments
lang-js