I making JavaScript 3D animation using actual style. I create working code but, i can't run the code if style is in extended CSS file, so code run only when style is written in HTML code. There is a solution?
Working code(olso on fiddle):
HTML
<div id="background">
<div class="example" style="transform-origin: 50% 50% -200px">
<p class="num">Example</p>
</div>
<div>
CSS
body {
display: inline-block;
background-color: black;
box-sizing: border-box;
}
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
.example {
display: inline-block;
position: absolute;
color: orange;
width: 100%;
font-size: 30px;
overflow: hidden;
white-space: nowrap;
font-size: 80px;
}
#background{
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
}
.example:nth-child(1){
transform: perspective(200px);
transform-origin: 50% 50% -200px;
}
.background {
display: inline-block;
position: absolute;
width: 100%;
height: 100%;
border-style: solid;
}
.num {
display: inline-block;
color: orange;
width: 50px;
height: 50px;
text-align: center;
}
JavaScript
setInterval(function(){ move()}, 2000);
function move(){
var elem = document.getElementsByClassName("example");
var str = elem[0].style.transformOrigin;
var res = str.split(" ");
var pos = res[2].replace(/px/g, " ");
var id = setInterval(frame, 20);
function frame(){
if (pos==500){
clearInterval(id);
}
else {
pos++;
elem[0].style.transformOrigin = "50% 50%"+pos+"px";
}
}
}
So as you see everything is working but, when i delete style from HTML code. I can see error in console: Cannot read property 'replace' of undefined
document.onload. Chances are, the JS runs before the CSS is loaded and so the CSS property doesn't exist.