About jQuery, why does the mouseenter() on a <input> not work?

680 views Asked by At

Thanks for checking my post first!

The mouseenter() is working for the tag h2, but it does not work on the <input>. Could you tell what is wrong with my code?

$(document).ready(function() {
  $("h2").mouseenter(function() {
    $(this).css("background-color", "green");
  });

  $("input").mouseenter(function() {
    $(this).css("background-color", "green");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <h2>Select Gaming Time:</h2>
  <form method="post">
    <input type="radio" name="time" value="5">5 Minute (Hard) &nbsp;&nbsp;&nbsp;&nbsp;
    <input type="radio" name="time" value="8">8 Minutes (Normal) &nbsp;&nbsp;&nbsp;&nbsp;
    <input type="radio" name="time" value="10">10 Minutes (Easy)
  </form>
</div>

2

There are 2 answers

1
BillyNate On BEST ANSWER

You are currently trying to turn the radio button's background green. Unfortunately this can't be done. You can however wrap the text next to the radios in a label and turn the label's background green.

As an added benefit you can make the label clickable as well using the for="" attribute and corresponding id=""s.

Also, this can be done using css only h2:hover, label:hover { background- color: green; }. Saving you a lot of bytes to load!

A. Wolff's code copied over from this jsfiddle:

$(document).ready(function () {
    $("h2").mouseenter(function () {
        $(this).css("background-color", "green");
    });

    $("label:has(:radio)").mouseenter(function () {
        $(this).css("background-color", "green");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
    
<h2>Select Gaming Time:</h2>

    <form method="post">
        <label for="time_5">
            <input type="radio" name="time" value="5" id="time_5">5 Minute (Hard) &nbsp;&nbsp;&nbsp;&nbsp;</label>
        <label for="time_8">
            <input type="radio" name="time" value="8" id="time_8">8 Minutes (Normal) &nbsp;&nbsp;&nbsp;&nbsp;</label>
        <label for="time_10">
            <input type="radio" name="time" value="10" id="time_10">10 Minutes (Easy)</label>
    </form>
</div>

0
collab-with-tushar-raj On

Well to avoid your confusion that mouseenter doesn't works on input type elements . This is not so . It works . You can see here . As said above in the answer , it is better to do the css change to the text next to radio button .