skip to Main Content

I produced some very basic code and wonder how it’s possible that one part of the function’s body works, while the other one doesn’t. Here is my code:

<!DOCTYPE html>
<html>

<body>
  <div id="id1">My Heading 1</div>

  <button type="button" onclick="changecolor()">Click Me!</button>

  <script>
    function changecolor() {
      var domElement = document.getElementById('id1');
      domElement.style.top = 100;
      domElement.style.color = 'red';
    }
  </script>
</body>

</html>

Changing the color works, but changing the position does not. Why is that?

3

Answers


  1. By default, HTML elements have position: 'static' which means that top has no effect whatsoever (documentation):

    • When position is set to absolute or fixed, the top property specifies the distance between the element’s outer margin of top edge and the inner border of the top edge of its containing block.
    • When position is set to relative, the top property specifies the distance the element’s top edge is moved below its normal position.
    • When position is set to sticky, the top property is used to compute the sticky-constraint rectangle.
    • When position is set to static, the top property has no effect.

    Change the position (e.g. domElement.style.position = 'absolute') as per your needs

    Additionaly, the top property needs to be a string and needs to have a unit, as per its syntax

    Login or Signup to reply.
  2. style.top is just expecting a string, not a number.

    In addition, you should ensure that style.position is set appropriately. The below modified code will achieve your desired result

    <!DOCTYPE html>
    <html>
    <body>
    
    <div id="id1">My Heading 1</div>
    
    <button type="button" 
    onclick="changecolor()">
    Click Me!</button>
    
    <script>
    function changecolor() {
        var domElement = document.getElementById('id1')
        domElement.style.position = 'relative';
        domElement.style.top = '100px'; 
        domElement.style.color = 'red'
    }
    </script>
    
    </body>
    </html>
    
    Login or Signup to reply.
  3. Elements with position: static (the default) do not honour properties like top; use e.g. value relative.

    Also, you are using a unit-less length, which I think is invalid.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search