Search code examples
javascriptjqueryonchange

jQuery CSS on change works only on click?


My initial settings for 'buttons' that are created in function are like this.

$(".save_w").css("color", "grey");
$(".save_w").css("pointer-events", "none");

HTML (simplified):

<input class="input_w" type="text">

<i class="save_w far fa-save"></i>

Next, function is simple :

$('body').on('change', '.input_w', function() {
  console.log("change");

  $(".save_w").css("pointer-events", "auto");
  $(".save_w").attr("color", "");
});

What I want to achieve

After changing the value of input with class "input_w", css of ".save_w" should be changed.

What I get

When I change value of input, the ".save_w" changes, but only after I click somewhere on the site (usually I click on another elements to trigger change). Why? There is no onclick method here.


Solution

  • Here is another example that uses input and CSS to make the changes a bit easier.

    $(function() {
      $('body').on('input', '.input_w', function() {
        if ($(this).val().length > 1) {
          $(".save_w").addClass("active");
        } else {
          $(".save_w").removeClass("active");
        }
      });
    });
    .save_w {
      color: gray;
      pointer-events: none;
    }
    
    .save_w.active {
      color: black;
      pointer-events: auto;
    }
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input class="input_w" type="text">
    
    <i class="save_w far fa-save"></i>