Reputation: 93
Since CSS can't handle sine or cosine calculations, I am using Math.sin
and Math.cos
inside a <script>
element in my HTML. I'm trying to use the results to position left
and top
. There just doesn't seem to be an easy solution. My code below works, but I can't use the results in a style element to position left
or top
.
<p id="GetHeight"></p>
<script>
function myCosFunction(b, angle) {
return Math.cos(angle*Math.PI / 180)*b;
}
document.getElementById("GetHeight").innerHTML = myCosFunction(240, 18);
</script>
Upvotes: 1
Views: 278
Reputation: 861
The other easy way to use the value from script
in CSS
is giving the innerHTML
to style
element using JS
as follows;
var size=parseInt(myCosFunction(80, 7));
document.getElementById('style').innerHTML="#box{margin-top:"+
size+"px;margin-left:"+
size+"px;height:100px;width:100px;background:red}";
function myCosFunction(b, angle) {
return Math.cos(angle*Math.PI / 180)*b;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style id="style">
</style>
</head>
<body>
<div id="box">
Me
</div>
</body>
<script src="js_function.js"></script>
</html>
Note: I have converted the value to int because the value used in CSS
properties should be discrete.
Update:
If you want to get margin-top
and margin-left
of box form a sin function then you can simply call the function for two times using two variables that is X and Y. Then you can change the parameters of calling function to get different values of X and Y;
var Y=parseInt(mySinFunction(280, 7));
var X=parseInt(mySinFunction(300, 7));
document.getElementById('style').innerHTML="#box{margin-top:"+
Y+"px;margin-left:"+
X+"px;height:100px;width:100px;background:red}";
function myCosFunction(b, angle) {
return Math.cos(angle*Math.PI / 180)*b;
}
function mySinFunction(b, angle) {
return Math.sin(angle*Math.PI / 180)*b;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style id="style">
</style>
</head>
<body>
<div id="box">
Me
</div>
</body>
<script src="sin_fun.js"></script>
</html>
Upvotes: 1
Reputation: 19562
You can use positioning like that
For apply left
CSS in GetHeight
id
document.getElementById("GetHeight").style.left = myCosFunction(240, 18);
same as for top
document.getElementById("GetHeight").style.top = myCosFunction(240, 18);
Upvotes: 1