0

I am trying to write some script that will allow the user to click on an object and each time they click it will increase in font-size by 1px.

It works fine until I try adding the while loop to add a size limit.

var fs = $(".word").css('fontSize');
$(".word").click(function() {
  while (fs <= "25px") {
    $(this).css('fontSize', (parseInt(fs) + 1) + 'px');
  }
});
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
lovelikelando
  • 7,593
  • 6
  • 32
  • 50

3 Answers3

0

JSBin

The reason your code doesn't work is about the condition. When you compare the value of string. Like '44px' < '12px' or '44px' < '123px', it always false.
Pay more attention the question.

while (fs <= "25px")

change to:

while (parseInt(fs) < 25)

Everything is ok!

Community
  • 1
  • 1
Todd Mark
  • 1,847
  • 13
  • 25
  • @self I have compared three tools to run web Server. http://jsfiddle.net/ and http://codepen.io/ and http://jsbin.com/. Finally, I found that JsBin is more quicly. Here is a article http://voidcanvas.com/jsbin-jsfiddle-or-codepen-which-one-to-use-and-why/rticle about reason. – Todd Mark Oct 13 '14 at 02:11
  • @GarrettMaring If you agree, please click **correct answer** – Todd Mark Oct 13 '14 at 02:34
  • I'm not a javascript expert but I believe the resulting while loop doesn't terminate. I guess the infinite loop just gets terminated at some point when it takes too much time. – Dennis van der Schagt Oct 13 '14 at 02:40
  • @GarrettMaring You don't need the while loop at all. Using an if statement is enough, so: `if (parseInt(fs) < 25)` – Dennis van der Schagt Oct 13 '14 at 02:45
  • Thank you all! It was a combo of two things as you guys pointed out. I needed to do the comparison with a `parseInt(fs)` and each time is was clicked i need to redefine `fs` from the updated css. – lovelikelando Oct 13 '14 at 02:51
-1
  • You are comparing an integer with a string, so something like 12 <= "25px". What you should do is comparing 2 integers.
  • You don't need a while loop here. You only have to increase the font size once per click, so one size check + increase is enough.
  • You should store the increased value of fs back into fs or get the updated font size using fs = parseInt($(".word").css('fontSize')) in the click function.

So one possible solution is:

var fs = parseInt($(".word").css('fontSize'));
$(".word").click(function(){
    if (fs <= 25){
        fs++;
        $(this).css('fontSize', toString(fs) + 'px');
    }
});
Dennis van der Schagt
  • 2,404
  • 2
  • 27
  • 33
-1

You're using string comparisons instead of numeric.

var fs = +$('.word').css('fontSize'); //gets actual number
while(fs <= 25) { //compares numbers
    $(this).css('fontSize', fs + 'px'); //the '+' coerces to string
    fs++; //increment the iterator
}
Jared Smith
  • 19,721
  • 5
  • 45
  • 83