Why does the string not moving within the certain interval?

49 views Asked by At

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>
3

There are 3 answers

1
Medet Tleukabiluly On BEST ANSWER

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>

1
Rayon On
  • line must be absolute positioned element so that left css property will affect
  • I assume you have not mentioned +px(unit) while assigning left property in interval as element.offsetWidth does not return unit with the value[Ref]
0
RunningFromShia On

Here is my shot:

<html>
<head>
    <title>Blablabla</title>
    <meta charset ="utf-8">
    <!-- <script type="text/javascript" src="line.js"></script> -->
</head>
<body>
    <div id="line">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
    </div>
<script type="text/javascript">
number = 5; //should be increased each time
setInterval(function(){var d = document.getElementById('line');
d.style.position = "absolute";
number++; //increase number
d.style.left = number; //move the div according to the number
}, 200); //notice that you can increase/decrease 200 according to your will

</script>
</body>
</html>