eow2898 eow2898 - 2 months ago 9
jQuery Question

CSS Transition on JS createElement() Working Intermittently

I'm using JavaScript to create a div and I'm adding

transition: .5s linear top;


onmousedown
, the div is supposed to move to the top and then it is deleted using JS
remove()
. Sometimes the transition works, sometimes not.

I suspect that something in the JS is causing it ... What am I missing?



var redBox = document.createElement("div"),
intSet;

document.onmousedown = function(){
intSet = setInterval("animate()", 1000);
}

document.onmouseup = function(){
clearInterval(intSet);
}

function animate(){
redBox.classList.add("redBox");
document.body.appendChild(redBox);

setTimeout (function() {
redBox.style.top = "0";
},0);

setTimeout (function(){
redBox.remove(redBox.selectedIndex);
},500);
}

.redBox{
background:red;
height: 100px;
width: 100px;
top: 300px;
position: absolute;
transition: .5s linear top;
}




Answer

I figured this out. Thanks to @Thomas.

var redBox = document.createElement("div"),
    intSet;

document.onmousedown = function(){
  intSet = setInterval("animate()", 1000);
}

document.onmouseup = function(){
  clearInterval(intSet);
}

function animate(){
  redBox.classList.add("redBox");
  document.body.appendChild(redBox);

    redBox.scrollWidth;
    redBox.style.top = "0";


  setTimeout (function(){
    redBox.remove(redBox.selectedIndex);
  },500);
}
.redBox{
  background:red;
  height: 100px;
  width: 100px;
  top: 300px;
  position: absolute;
  transition: .5s linear top;
}

I replaced the setTimeout(function(){},0); with redBox.scrollWidth;. The CSS animation is now running smoothly ;)

Comments