1

I am trying to re-size the font size of one of my divs in jquery using an input. Ideally, the number put inside the input box would be added on to the existing font size but so far my attempts have been unsuccessful.

Here is what I have so far but it does not seem to be working:

HTML

<div class="resizeable" style="font-size: 30px;">test</div>
<input type="text" name="size" class="size" />

JQuery

$(document).ready(function() {
    $('.size').keyup(function() {
        var currentFontSize = $('this').css('font-size');
        var input = $(this).val(); // grab the input value
        var newsize = input + currentFontSize;
        console.log(size);

        if ($(this).val().length > 0)
        {
            // replace css value on live preview 
            $('.resizeable').css('font-size', newsize);  
        } 
    }); 
});

JSFiddle http://jsfiddle.net/eqE2R/36/

Any help would be appreciated.

2 Answers 2

2

You need to add px value and use parseInt() for addition:

$('.size').keyup(function() {
    var currentFontSize = $('.resizeable').css('font-size');
    var input = $(this).val(); // grab the input value
       alert(currentFontSize)
    var newsize =parseInt(input,10) + parseInt(currentFontSize,10);
    console.log(newsize);

    if ($(this).val().length > 0)
    {
        // replace css value on live preview 
        $('.resizeable').css('font-size', newsize + 'px');  
    } 
  }); 

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

FIDDLE

You forgot to add px to the value. You must also parse the values to the int

$(document).ready(function() {
    var currentFontSize = $('.resizeable').css('font-size');
    $('.size').keyup(function() {
        var input = $(this).val(); // grab the input value
        var newsize = parseInt(input) + parseInt(currentFontSize);

        if ($(this).val().length > 0)
        {
            // replace css value on live preview 
            $('.resizeable').css('font-size', newsize + 'px');  
        } 
    }); 
});

EDIT: I moved the currentFontSize variable deifnition outside the keyup function, so it will be declared only once at the begining.

4 Comments

Thanks! That fixed it. The only problem now is that it is always adding to the size and won't downsize. Ex: change from 10 to 5 will make it 15.
That's right. You added currentFontSize to the newsize. You want it to be back 30px when the input is empty?
Ideally, I want it to be able to reduce in size if the new value is greater than the last value but I want to avoid hard coding the original size in the jquery.
Thanks! I am still learning JQuery. Hopefully I will get the hang of it soon :D

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.