-1

I want to remove the glitch class after one second. I tried to solve it with setTimeout but it didn't work. The class wasn't removed on mouseleave.

$(document).ready(function (e) {
  $('.glident').hover(function() { 
    $(this).addClass('glitch') 
  }, function() { 
    $(this).removeClass('glitch') 
  })
});

Thats what I tried to do:

$(document).ready(function () {

$('.glident').mouseover(
    function () {
        $(this).addClass('glitch')
    }
);

$('.glident').mouseout(
    setTimeout(function () {
        $(this).removeClass('glitch');
    }, 1000)
);

});
  • Remember we're here to help you fix bugs, not to write code for you. Could you please show the code you wrote that used `setTimeout()` – Rory McCrossan Feb 22 '18 at 13:13
  • Welcome to Stack Overflow! Please take the [tour] and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) You've said you've tried; show us that. Otherwise: Do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Feb 22 '18 at 13:13
  • 1
    I suspect the problem you were having was this: http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – T.J. Crowder Feb 22 '18 at 13:14

1 Answers1

0

mistake is here

$('.glident').mouseout(
    setTimeout(function () {

settimeout executes when page loads without waiting for event to occur

$(document).ready(function(){
    $("button").mouseover(function(){
        setTimeout(function(){$("p").removeClass("intro");
    },1000)
     });
     $('button').mouseleave(function () {
        $("p").addClass('intro');
    });

});
.intro {
    color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>

<h1>This is a heading</h1>

<p class="intro">This is a paragraph.</p>
<p class="intro">This is another paragraph.</p>

<button>Remove the "intro" class from all p elements</button>

</body>
</html>

The class wasn't removed on mouseleave.

Unlike the mouseleave event, the mouseout event is triggered if a mouse pointer leaves any child elements as well as the selected element. The mouseleave event only triggers when the mouse pointer leaves the selected element. See the example at the end of the page for a demonstration.

jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22