skip to Main Content

This code seems not to work.

The text stays blue on hover, but I want it to be red instead after clicking this text.

Tried several actions, but none of them works

$('.secondary').click(function() {
  $(this).unbind('mouseenter mouseleave');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style media="screen">
  .secondary {
    color: red;
    font-weight: bold;
    position: relative;
  }
  
  .secondary:hover {
    color: blue;
  }
</style>

<div class="secondary">
  CLICK ME TO BE RED
</div>

2

Answers


  1. $('.secondary').click(function() {
      $(this).removeClass('hover');
    });
    .secondary {
      color: red;
      font-weight: bold;
      position: relative;
    }
    
    .hover:hover {
      color: blue;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    <div class="secondary hover">
      CLICK ME TO BE RED
    </div>
    Login or Signup to reply.
  2. You can use mouseenter and mouseleave events and remove said events with a click event as well, like so:

    $('.secondary').on({
      mouseenter: function() {
        $(this).css('color', 'blue');
      },
      mouseleave: function() {
        $(this).css('color', 'red');
      },
      click: function() {
        $(this).off('mouseenter mouseleave');
        $(this).css('color', 'red');
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style media="screen">
      .secondary {
        color: red;
        font-weight: bold;
        position: relative;
      }
    </style>
    
    <div class="secondary">
      CLICK ME TO BE RED
    </div>

    I would suggest adding/removing a class with your preferred styling instead of applying CSS through JavaScript, though. You can achieve that like so:

    $('.secondary').on({
      mouseenter: function() {
        $(this).addClass('is-blue');
      },
      mouseleave: function() {
        $(this).removeClass('is-blue');
      },
      click: function() {
        $(this).off('mouseenter mouseleave');
        $(this).removeClass('is-blue');
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <style media="screen">
      .secondary {
        color: red;
        font-weight: bold;
        position: relative;
      }
      
      .secondary.is-blue {
        color: blue;
      }
    </style>
    
    <div class="secondary">
      CLICK ME TO BE RED
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search