2

I have a trouble with my code. I want to do when i click on div that gets some class and after 1 second it removes that class. Here is example of my code:

$(document).ready(function() {
  alert('aaa');
  $(document).on("click", ".items-layout > div", function() {
    var $this = $(this);
    $this.addClass('hover-effect');
    $this.off("click");
  }, function() {
    setTimeout(function() {
      var $self = $(this);
      $self.removeClass('hover-effect');
      alert('yolo');
    }, 1000);
});

2 Answers 2

4
$(document).ready(function() {
alert('aaa');
$(document).on("click", ".items-layout > div", function() {
        var $this = $(this);
        $this.addClass('hover-effect').off("click");
        setTimeout(function() {
            $this.removeClass('hover-effect');
            alert('yolo');
        }, 1000);
});

what was wrong:

you passed into .on('click' two functions. But you can pass only one (Second just ignored). So you need to move code from the second one into the first one. That's what I did

Sign up to request clarification or add additional context in comments.

2 Comments

Any explanantion of the problem and why this fixes it?
@RoryMcCrossan sure
0

Try this ...

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .hover-effect{
                background-color: #00733e;
            }
            .normal-effect{
                color: #000000;
                background-color: #ffffff;
            }
        </style>
    </head>
    <body>
        <div class="items-layout">
            <div>sample</div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                alert('aaa');
                $(document).on("click", ".items-layout > div", function () {
                    var $this = $(this);
                    console.log($this);
                    $this.addClass('hover-effect');
                    $this.off("click");
                    setTimeout(function () {
                        var $self = $(this);
                        $self.removeClass('hover-effect');
                        $this.addClass('normal-effect');
                        alert('yolo');
                    }, 1000);
                });
            });
        </script>
    </body>
</html>

Thank you ...

1 Comment

in your case var $self = $(this); will save incorrect context cause this is either window / undefined