Using CSS calc () with .animate ()
I'm trying to make a small animation, but I can't make it responsive because "calc ()" doesn't seem to work with .animate. Is there any other solution for this here?
if (time == 1) {
$("#message").animate({ marginTop: "calc(-15px + .8vw)" });
} else {
$("#message").animate({ marginTop: "calc(0px + .8vw)" });
}
Best wishes, BERNARDO
EDIT: I am trying to animate a message that appears on my website onchange () in a dropdown menu. It should be responsive so that I use 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 an alternative to make it responsive in a different way without calc ()?
source to share
Since vw
is a unit equal to 1% of the viewport width, we can evaluate the statements calc()
to a value that 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>
source to share
Here is a JavaScript alternative for calc()
.
Basically I am calculating my values ββin vw units with this line:
var vw_value = $(window).width() / 100 * 0.8;
Working violin here. Just change the variable time
to 0 to see the difference:
var time = 0;
var vw_value = $(window).width() / 100 * 0.8;
if (time == 1) {
$("#one").animate({ marginTop: vw_value - 15 + "px" });
} else {
$("#one").animate({ marginTop: vw_value + "px" });
}
body{
margin:0;
padding:0;
}
#one{
margin-top:0;
width: 40px;
background:grey;
height:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="one"></div>
source to share