Question

I've written a code that displays 2 buttons and one text. When we click on the button, "GROW" the size of the text should grow and when we click, "SHRINK" the size should reduce. But this is working only for one click. When I click second time, the functions are not invoked. Why is this happening? Here is the code for it..

<html>
<head>
    <script type="text/javascript">
        function Grow()
        {
            var a=document.getElementById(1);
            a.style.fontSize=a.style.fontSize+50;

        }
        function Shrink()
        {
            var a=document.getElementById(1);
            a.style.fontSize=20;

        }
    </script>
</head>
<body>
    <input type="button" value="grow" onclick="Grow()">
    <input type="button" value="shrink" onclick="Shrink()">
    <p id="1"> Hello </p>
</body>

Was it helpful?

Solution

When you perform the grow action for the first time it automatically uses the units px as you started off with a null value. You will need to parse the value of .fontSize before you can perform arithmetic on it. Try this...

parseInt(a.style.fontSize.replace('px', ''));

to get a numerical value you can perform arithmetic on.

In full...

function Grow()
{
    var a=document.getElementById(1);

    // Get a number we can perform arithmetic on
    size = parseInt(a.style.fontSize.replace('px',''));

    // Additional check needed because original dimensions not specified
    if (!isNaN(size)) { // If we now have a number we can use
        a.style.fontSize=size+50;
    } else { // Otherwise, set to 50 (assuming we are starting from 0px)
        a.style.fontSize=50;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top