1

I am trying to make a smooth effect onClick using CSS. When I click the button, this .mobileNav class will be added by jQuery addClass method. This works fine.

But CSS transition is not working well

This is What tried so far

<button class="mobileNav">button</button>
    
.menu {
  position: absolute;
  top:60px;
  right:-250px;
  transition:right 1s linear;
}
.menu.mobileNav {
  right:0;
}

CSS transition is not smooth. What is wrong my code?

bad_coder
  • 11,289
  • 20
  • 44
  • 72
user1833620
  • 751
  • 1
  • 10
  • 30

2 Answers2

1

I think you did not add the class .menu to your button, that's why the transition wasn't working, because the transition was added to .menu not to .menu.mobileNav, well, it's working here now, lemme know if it works for you too

$(".menu").on('click', function () {
    $(".menu").addClass('mobileNav');
});
body {
  width: 100px;
  margin: 20px;
  position: relative
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
  .menu {
    position: absolute;
    top:60px;
    right:-250px;
    transition: right 1s linear;
  }
  
  .menu.mobileNav {
    right: 0;
  }
</style>

<body>
  <button class="menu">button</button>
</body>
Tanim
  • 1,256
  • 8
  • 14
0

Well properties like left, top, bottom and right are not hardware accelerated. That means your CPU needs to perform this transition on its own without the help of the GPU (if you have one witch you usually have)

For this case i would use simply transform witch uses hardware acceleration:

.menu { position: absolute; top:60px; transform: translateX(-250px); transition:transform 1s linear; }
.menu.mobileNav { transform: translateX(0) }

Take a look at this guys answer

bill.gates
  • 14,145
  • 3
  • 19
  • 47