From the jQuery API documentation:
The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases. (https://api.jquery.com/delay/)
It is not perfectly documented (as far as I can tell), but toggleClass()
is not a function that uses the built-in effects queue.
Easiest solution is to use the vanilla window.setTimeout()
function:
$( document ).ready(function() {
console.log("ready!");
$("#search-form").hover(function() {
window.setTimeout(function() {
$("#search-input").toggleClass("collapse");
}, 700)
});
});
PS: The above solution, while it will technically work, it will not behave how you'd expect to, when you're moving fast on/off the form with the mouse pointer. See the simulation below:
$( document ).ready(function() {
console.log("ready!");
$("#search-form").hover(function() {
window.setTimeout(function() {
$("#search-input").toggleClass("collapse");
}, 700)
});
});
/* Border - just to highlight the form */
#search-form {
border: 2px solid red;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search-form" style="display:flex-end;" class="form-inline my-2 my-lg-0">
<button class="btn btn-search" type="submit" data-toggle="collapse">BUTTON
</button>
<input id="search-input" class="collapse form-control" type="text" placeholder="Search..." name="search">
</form>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…