Home > Software design >  transition doesn't work editing while window onload
transition doesn't work editing while window onload

Time:11-17

I'm trying to move this square to right 100px after clicking on it with js, I've set the transition to 1s, but it doesn't work

window.onload = function(){
    var square = document.querySelector(".square");        
    square.onclick = function(){
        square.style.right = "100px";
    };
};
.square {
    position: absolute;
    background-color: red;
    width: 500px;
    height: 500px;
    transition: 1s;
}
<div class="square">
</div> 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

CSS won't animate things from auto to px.
Since right is not defined, it's defaulting to auto.

window.onload = function(){
    var square = document.querySelector(".square");        
    square.onclick = function(){
        square.style.right = "100px";
    };
};
.square {
    position: absolute;
    background-color: red;
    width: 500px;
    height: 500px;
    right: 0;
    transition: 1s;
}
<div class="square">
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

However, if you want to animate it without setting right at the beginning, you can also use translate.

window.onload = function(){
    var square = document.querySelector(".square");        
    square.onclick = function(){
        square.style.transform = "translateX(100px)";
    };
};
.square {
    position: absolute;
    background-color: red;
    width: 500px;
    height: 500px;
    transition: 1s;
}
<div class="square">
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related