Search code examples
javascripthtmljquerycssmargin

Margin Reset to 0 in 1 Second


When you click the button once the transition is 300 seconds.

What i'm trying to do is when you click the button twice Reset it in 1 second

So what is happening is when you click the button once Margin-Left goes -20000px in 300 seconds ..what i want is when you click it twice it resets Margin-Left to 0 in 1 second not 300.

var clicked1 = 0;
const btn = document.getElementById("blast")

function screen() {
  if (clicked1 == 0) {
    $(".box").toggleClass("boxxy", 0);
    btn.textContent = btn.textContent === "RETURN HOME" ? "FLY AWAY" : "RETURN HOME";
    clicked1 = 1;
  } else if (clicked1 == 1) {
    $(".box").toggleClass("boxxy", 0);
    btn.textContent = btn.textContent === "RETURN HOME" ? "FLY AWAY" : "RETURN HOME";
    clicked1 = 0;
  }
}
body {
  background-color: #6A6A6A;
}

html,
body {
  height: 100%;
}

.boxxy {
  margin-left: -20000px;
  transition-duration: 1s;
}

.box {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 20000px;
  height: calc(100% - 100px);
  overflow: hidden;
  transition-timing-function: linear;
  transition-duration: 300s;
  z-index: 5;
}

.box img {
  height: 100%;
  width: 100%;
}

.linksbox {
  position: fixed;
  bottom: 0px;
  left: 0px;
  width: 100%;
  height: 100px;
  text-align: center;
  background-color: #000000;
  font-size: 25px;
  color: #AEBC1F;
}
<div id="box" class="box">
  <img src="https://tim-school.com/codepen/2dgame/wall.png" alt="" />
</div>
<div class="linksbox">
  <button onClick="screen()" id="blast">FLY AWAY</button>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>


Solution

  • Adding this condition in css should be enough:

    .boxxy {
      margin-left: -20000px;
      transition-duration: 1s;
    }
    
    .box:not(.boxxy) {
      margin-left: 0px;
      transition-duration: 300ms;
    }
    

    When you add the class .boxxy the transition-duration: 1s; will be applied and when you remove that class the conditions for .box:not(.boxxy) will be applied.