Thread: I need a tiny bit of help with JavaScript

Reply to Thread
Results 1 to 2 of 2
  1. #1 I need a tiny bit of help with JavaScript 
    Senior Member Karim D. Ghantous's Avatar
    Join Date
    Oct 2011
    Location
    Melbourne AU
    Posts
    1,906
    Here's some code which does nothing more complicated than change the size of the text in an element:

    Code:
    <body>
    
    <p id="demo">This text will change size when you press the button.</p>
    
    <script>
    
    function myFunction()
    {
    var a = "30px"; //this is a string
    var b = 15; //but this is a number
    var c = 15;
    var d = b+c;
      document.getElementById("demo").style.fontSize = a; 
    }
    
    </script>
    
    <button type="button" onclick="myFunction()">Click</button>
    
    </body>
    See the line in yellow? Try changing a to b, c or d. It doesn't work. So, what am I missing? I've tried a few things but nothing worked.

    I'm having a hard time searching for this type of problem so I'm hoping someone here knows.
    Good production values may not be noticed. Bad production values will be.
    Pinterest
    | Flickr | Instagram | 1961 (blog)
    Reply With Quote  
     

  2. #2  
    Senior Member Alex Lubensky's Avatar
    Join Date
    Nov 2016
    Location
    Kiev, Ukraine
    Posts
    197
    You can't use numbers to set fontSize, only strings like in var a.

    If you need to use numbers to add, then you need to convert numbers to a string like in this example:

    <body>

    <p id="demo">This text will change size when you press the button.</p>

    <script>

    function myFunction()
    {
    var a = "30px"; //this is a string
    var b = 15; //but this is a number
    var c = 15;
    var d = b+c;
    var result_b = String(b) + "px";
    var result_c = String(c) + "px";
    var result_d = String(d) + "px";
    document.getElementById("demo").style.fontSize = result_d;
    }

    </script>

    <button type="button" onclick="myFunction()">Click</button>

    </body>
    Last edited by Alex Lubensky; 06-24-2020 at 01:53 AM.
    Reply With Quote  
     

Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts