-1

I want to move an element from top to bottom, adding 1px to its top every 10millisecond using setInterval

This is my code:

var cir1 = document.getElementsByClassName('cir1');

function moveCir(elem) {
    var elemTop = elem.style.top + 'px';
    elem.style.top = elemTop;
    elem.style.top = elemTop + 1 + 'px' ;
    setInterval(function () {
        moveCir(elem)
    },10)
}
.cir1 {
    height: 100px;
    width: 100px;
    margin: 30px 100px;
    border: 1px solid #AC0D67;
    border-radius: 100%;
    display: inline-block;
}
<button onclick="moveCir(cir1)" id="start">Start</button>
<div class="cir1"></div>

But I cant find out why its not working

Yoshi
  • 54,081
  • 14
  • 89
  • 103
Reza Poorbaferani
  • 121
  • 1
  • 3
  • 11

2 Answers2

1

i guess you want this:

function moveCir(elem) {
  var elemTop = elem.getBoundingClientRect().top;
  if (elemTop < 200) {
    elem.style.top = elemTop + 1 + 'px';
    setTimeout(function() {
      moveCir(elem)
    }, 100)
  }
}
#cir1 {
  height: 100px;
  width: 100px;
  margin: 30px 100px;
  border: 1px solid #AC0D67;
  border-radius: 100%;
  display: inline-block;
  position: absolute;
}
<button onclick="moveCir(cir1)" id="start">Start</button>
<div id="cir1"></div>

however,i have to warn you :

this is a bad idea :

onclick="moveCir(cir1)"

a better solution is here:

var moveCir = function f(elem) {
  var elemTop = elem.getBoundingClientRect().top;
  if (elemTop < 200) {
    cir1.style.top = elemTop + 1 + 'px';
    setTimeout(f, 100, elem);
  }
};

var cir1 = document.getElementById('cir1');
document.getElementById('start').addEventListener('click', function() {
  moveCir(cir1)
}, false);
#cir1 {
  height: 100px;
  width: 100px;
  margin: 30px 100px;
  border: 1px solid #AC0D67;
  border-radius: 100%;
  display: inline-block;
  position: absolute;
}
<button id="start">Start</button>
<div id="cir1"></div>
xianshenglu
  • 4,943
  • 3
  • 17
  • 34
0
var cir = document.getElementsByClassName('cir1')[0];
var cirTop = cir.style.top;
function moveCir() {
cirTop++;
cir.style.top = cirTop + 'px';
}
setInterval(moveCir, 10);

class names are taken as an array. You have not included [0] in document.getElementsByClassName('cir1')

RemyShad
  • 23
  • 1
  • 4