Shawn -
Shawn -

Reputation: 109

How to stop hover when I click anchor?

$(function() {

  $("a").hover(function() {
    $(this).css("color", "red");
  }, function() {
    $(this).css("color", "green");
  });

  $("a").click(function() {

    $("a").off("hover");

  })



})
body {
  display: flex;
  justify-content: center;
  margin-top: 300px;
}

a {
  font-size: 30px;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<ul>
  <li><a>one</a></li><br><br>
  <li><a>two</a></li><br><br>
  <li><a>three</a></li><br><br>
</ul>

I want to stop hover when click anchor.

Just stop hover work. but I use off(), still hover.

I even used stop(), or remove(), and still doesn't work.

How do I stop hover when I click anchor?

Upvotes: 0

Views: 87

Answers (2)

1jovi3
1jovi3

Reputation: 104

The solution i have is using JavaScript. This is one example.

$('div').on('click', function() { // when you click the div
$(this).addClass('no-hover'); // add the class 'no-hover'
});
div {
  color: blue;
}
div:not(.no-hover):hover { /* only apply hover styling when the div does not have the 
class 'no-hover' */
  color: red;
}

Upvotes: 1

Swati
Swati

Reputation: 28522

You can add some class whenever you click on a tag and then put a condition to check if the anchor which is hover doesn't have that class using hasClass().

Demo Code :

$(function() {

  $("a").hover(function() {
    //check if a has the class added
    //if only need one time just use `a` instead of `this`
    if (!$(this).hasClass("hover_already")) {
      $(this).css("color", "red");
    }
  }, function() {
    $(this).css("color", "green");
  });

  $("a").click(function() {
    //add some class or if you need to remove it use `toggleClass` after second click
    $(this).addClass("hover_already");
  })
})
body {
  display: flex;
  justify-content: center;
  margin-top: 300px;
}

a {
  font-size: 30px;
}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<ul>
  <li><a>one</a></li><br><br>
  <li><a>two</a></li><br><br>
  <li><a>three</a></li><br><br>
</ul>

Upvotes: 1

Related Questions