2

I need to add a delay to .addClass and .removeClass for 200ms here:

jQuery('.class').hover(() => jQuery('#custom').addClass('addedclass'), () => jQuery('#custom').removeClass('addedclass'));

I tried this example jQuery: Can I call delay() between addClass() and such? but the structure there is slightly different.

twelvell
  • 257
  • 1
  • 8
  • 19
  • At which point to you want the delay to occur? `hover`'s first argument occurs when the mouse cursor enters the element, and the second argument is called when the mouse cursor leaves the element. Adding a delay between them doesn't make a lot of sense. If you want to delay the removal of the class after the the mouse has left the element, one of the answers to the linked post should work fine: https://stackoverflow.com/a/27623259/215552 – Heretic Monkey Feb 09 '20 at 02:21
  • I needed to shortly delay the class addition on hover and also delay it when mouse it not hovering it. To lose the instant appearance. – twelvell Feb 09 '20 at 02:26

1 Answers1

2

You can use setTimeout to achieve it.

jQuery('.class').hover(
() => setTimeout(() => jQuery('#custom').addClass('addedclass'), 200), 

() => setTimeout(() => jQuery('#custom').removeClass('addedclass'), 200));
.addedclass{
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="class">
  <p id="custom">Text</p>
</div>
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56