I am trying to make a simple code of a line moving 1px every 20 milliseconds (smt like a ticker) . Also, want it to disappear once it reaches the edge of the browser window using .offsetWidth property. Unfortunately, I'm stuck and I don't know why it's not moving at all. Please, help me find the mistake, or maybe I'm going in the wrong direction? Thanks!
<html>
<head>
<title>Blablabla</title>
<meta charset ="utf-8">
<!-- <script type="text/javascript" src="line.js"></script> -->
</head>
<body onload="interval()">
<div id="line">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</div>
<script type="text/javascript">
function interval() {
var line = setInterval(function(){document.getElementById("line").style.left = scroll.offsetWidth}, 20);
}
</script>
</body>
</html>
Take a look at sample below, it has comments that should help you to understand, checkout demo and play around with code
//set starting offset
var leftOffset = 0;
//assign element to variable
var element = document.getElementById("line");
//css.left requires position.absolute
element.style.position = 'absolute';
//calculate width of element, in display.block it's 100%
element.style.display = 'inline-block';
//assign interval id to a variable for cancelation
var interval = setInterval(function(){
//increase offset by 1
leftOffset = leftOffset + 1;
//check if element is sticked to screen.right
if(leftOffset + element.offsetWidth < document.body.offsetWidth) {
//not sticked
//add pixels
element.style.left = leftOffset + 'px';
} else {
//sticked
//remove interval
clearInterval(interval);
//hide element
element.style.display = 'none';
}
}, 20);
<div id="line">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
</div>