skip to Main Content

Please tell me why I can’t set the scale for the div?

var a = 0.1;
var b = 0.1;
var scale = a+b;
$(".item").css('scale', scale)
.item {
  width: 100px;
  height: 100px;
  background: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item"></div>

2

Answers


  1. As per the documentation :

    When a number is passed as the value, jQuery will convert it to a string and add px to the end of that string. If the property requires units other than px, convert the value to a string and add the appropriate units before calling the method.

    Thus, the parameter has to be a string, not a number :

    var a = 0.1;
    var b = 0.1;
    var scale = a+b;
    $(".item").css('scale', scale.toString())
    .item {
      width: 100px;
      height: 100px;
      background: blue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="item"></div>
    Login or Signup to reply.
  2. Besides you need to pass as string like .css("scale", `${scale}`) or .css("scale", scale.toString()) (as already suggested by @Tom),..

    you don’t need jQuery for that task, just plain JS and CSS Var:

    const a = 0.1;
    const b = 0.1;
    const scale = a + b;
    
    document.querySelectorAll(".item").forEach((elItem) => {
      elItem.style.setProperty("--scale", scale);
    });
    .item {
      width: 100px;
      height: 100px;
      background: blue;
      scale: var(--scale, 1); /* Use --scale CSSVar or default to 1 */
    }
    <div class="item"></div>

    MDN: Using CSS custom properties
    MDN: CSS var()

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