Changing src image on button on mouseover

I want to change my img src when I hover over a button.

There are several answers similar to mine,

but I still can't figure it out.

<button class='Nav' id="Nav_Homepage">
    <img src="./img/Homepage.png" class='img_Nav' id="img_Homepage">
    <label class='lb_Nav'> Homepage </label>
</button>

      

+3


source to share


3 answers


You can do it with CSS



#Nav_Homepage span {
  background: url(https://dummyimage.com/20x20/000/fff.png&text=P) no-repeat;
  width: 20px;  /* your image width */
  height: 20px; /* your image height */
  display: inline-block;
}
#Nav_Homepage label {
  display: inline-block;
}
#Nav_Homepage:hover span {
  background: url(https://dummyimage.com/20x20/ff0000/ffffff.png&text=H) no-repeat;
}
      

<button class='Nav' id="Nav_Homepage">
    <span class='img_Nav'></span>
    <label class='lb_Nav'> Homepage </label>
</button>
      

Run codeHide result


+7


source


If you have a new image source just use this code. use this method if you want to change an image with multiple images.



$('#btn_id')

.on('mouseenter', function() {
    $('#img_Homepage').attr('src', 'url_of_new_image');
})

.on('mouseleave', function() {
    $('#img_Homepage').attr('src', 'url_of_old_image');
});

      

+6


source


$(document).ready(function() {
  $("#Nav_Homepage").mouseenter(function() {
    $(this).children('img').attr("src", "./img/newimage.png");
  });
  $("#Nav_Homepage").mouseleave(function() {
    $(this).children('img').attr("src", "./img/Homepage.png");
  });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class='Nav' id="Nav_Homepage">
    <img src="./img/Homepage.png" class='img_Nav' id="img_Homepage">
    <label class='lb_Nav'> Homepage </label>
</button>
      

Run codeHide result


+3


source







All Articles