'mouseenter doesn't get fired first time [closed]
When i go to part where the mouseenter is it doesn't get fired first time. But if i leave it and return and to the same part, then the mouseenter gets fired. I been desperately looking for a solution. The code part looks like this
if(target.hasClass("level1")) {
console.log(target);
target.mouseenter(function () {
newThis.focus(event, target);
timer = setTimeout(function () {
newThis.focus(event, target);
}, 200);
}).mouseleave(function () {
clearTimeout(timer);
});
}
So yeah, the code works, but it doesnt get fired the first time.
Solution 1:[1]
That's intentional: it only fires on crossing the boundary upon entering.
Does the mouseover event solve your problem?
Solution 2:[2]
You are creating the .mouseenter and .mouseleave handler within an if. So once the if statement is fullfilled you set mouse enter/leave handlers.
This means the events will only fire after the if was executed. So another mouse movement is required to trigger the newly added event.
You will typically create the handlers when loading the page and filtering inappropriate calls later.
Without knowing further context - try a concept where you don't need the if.
See example below.
let timer;
$('.level1')
.mouseenter(function (event) {
var newThis = $(this).find('input');
newThis.focus();
timer = setTimeout(function () {
newThis.focus();
}, 200);
}).mouseleave(function () {
clearTimeout(timer);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<article>
<section>
<h1>Hello.</h1>
<p>Article Text</p>
</section>
<section>
<form>
<div class="level1">
<input type="text" name="one" />
</div>
<div class="level2">
<input type="text" name="two" />
</div>
</form>
</section>
</article>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tbjgolden |
| Solution 2 | Peter Krebs |
