JS Translate onclick

When I first click the button it shows the hidden container but with no transition. On each consecutive click the transitions works fine.

function myFunction() {
  var x = document.getElementById("hidden-div-1");
  if (x.style.transform === "translateY(0)") {
    x.style.transform = "translateY(100%)";
  } else {
    x.style.transform = "translateY(0)";
  }
}
//moves the 2nd div out of the way
function myFunction1() {
  document.getElementById("hidden-div-1").style.transition = "all .5s";
  document.getElementById("hidden-div-1").style.transform = "translateY(100%)";
}

CSS For that element is:

transform: translateY(100%);
    
>! background-color: saddlebrown;
>! grid-column: col-st 1 / col-nd 6;
>! grid-row: 1 / 16;
>! z-index: 4;

I’ve spent some time on the code, but I’m not very well versed with JS and I got stuck

  • On the first run through, the x.style.transform probably does not equal "translateY(0)" (it’s probably null/undefined/”” etc). Switch your if around and look for the known value"translateY(100%)". Or debug and see what it does equal.

    – 

  • 1

    document.getElementById("hidden-div-1").style.transition = "all .5s" this should be added by default. Just add transition: all .5s to your css file

    – 




  • Thank you Konrad. That did the trick

    – 

Leave a Comment