0

I use images to replace the label for the checkbox, but I don't know how to change the images when the mouse is hovered using external js.

<fieldset id="box">
  <legend>choices</legend>
  <ul id="container">

    <li id="ch1">
      <input id="check1" type="checkbox" />
      <label class="cb" for="check1"> 1 </label>


    </li>

    <li id="ch2">
      <input id="check2" type="checkbox" />
      <label class="cb" for="check2">2</label>

    </li>

    <li id="ch3">
      <input id="check3" type="checkbox" />
      <label class="cb" for="check3">3 </label>

    </li>
  </ul>

</fieldset>

2 Answers 2

1

a.jpg represents your original image SRC and b.jpg represents the new image src.

Be sure to load with the defer tag! (<script defer src="..."></script>)

var checkboxes = document.querySelectorAll('input[type="checkbox"]');
var labels = document.querySelectorAll('label');

for (var i = 0; i < checkboxes.length; i++) {
    checkboxes[i].addEventListener('mouseover', function () {
        var label = this.nextElementSibling;
        label.src = 'b.png';
    });
    checkboxes[i].addEventListener('mouseout', function () {
        var label = this.nextElementSibling;
        label.src = 'a.png';
    });
}

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

Comments

0

Optionally, CSS can do this as well:

.cb {
  background-size: contain;
  display: inline-block;
  width: 75px;
  height: 75px;
}

/* Just an example - you would split these up to use different images, like the lines using :hover below */
#ch1>.cb,
#ch2>.cb,
#ch3>.cb {
  background-image: url('https://via.placeholder.com/75');
}

#ch1:hover>.cb {
  background-image: url('https://via.placeholder.com/100');
}

#ch2:hover>.cb {
  background-image: url('https://via.placeholder.com/200');
}

#ch3:hover>.cb {
  background-image: url('https://via.placeholder.com/300');
}
<fieldset id="box">
  <legend>choices</legend>
  <ul id="container">
    <li id="ch1">
      <input id="check1" type="checkbox" />
      <label class="cb" for="check1"></label>
    </li>
    <li id="ch2">
      <input id="check2" type="checkbox" />
      <label class="cb" for="check2"></label>
    </li>
    <li id="ch3">
      <input id="check3" type="checkbox" />
      <label class="cb" for="check3"></label>
    </li>
  </ul>
</fieldset>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.