Search code examples
jquerycssjquery-animatecss-calc

Using CSS calc() with .animate()


I'm trying to make a little animation but I'm failing to make it responsive, because "calc()" seems to not work with .animate. Is there another solution to this here?

if (time == 1) {
  $("#message").animate({ marginTop: "calc(-15px + .8vw)" });
} else {
  $("#message").animate({ marginTop: "calc(0px + .8vw)" });
}

With great and best regards, BERNARDO

EDIT: I'm trying to animate a message that appears on my website onchange() of a dropdown menu. It should be responsive so that's why I'm using calc().

<a>Time: </a><select id="time" onchange="setTime()" name="time" required>
                    <option value="1" selected>-</option>
                    <option value="3">-</option>
              </select></br>

So is there like an alternative to make it responsive on another way without calc()?


Solution

  • Since vw is a unit of measure equal to 1% of the width of the viewport, we can calculate the calc() statements into a value jQuery can understand.

    var time = true
    
    $('#toggle').click(function () {
      time = !time;
      
      if (time === true) {
        // calc(-15px + .8vw)
        var calc = -15 + (0.08 * $(window).width()) + "px";
        $("#message").animate({ marginTop: calc });
      } else {
        // calc(0px + .8vw)
        var calc = 0 + (0.08 * $(window).width()) + "px";
        $("#message").animate({ marginTop: calc });
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="toggle">Toggle</button>
    <div id="message">Message</div>