Home > Net >  How to change the background image with mouseover using external js?
How to change the background image with mouseover using external js?

Time:10-10

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  for="check1"> 1 </label>


    </li>

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

    </li>

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

    </li>
  </ul>

</fieldset>

CodePudding user response:

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';
    });
}

CodePudding user response:

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  for="check1"></label>
    </li>
    <li id="ch2">
      <input id="check2" type="checkbox" />
      <label  for="check2"></label>
    </li>
    <li id="ch3">
      <input id="check3" type="checkbox" />
      <label  for="check3"></label>
    </li>
  </ul>
</fieldset>

  • Related