0

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
3
  • What is the console error message? Commented May 3, 2014 at 5:31
  • still no resizing happening even after changing this.value; to your suggestion Commented 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 undefined Commented May 3, 2014 at 5:34

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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