3

I want to change my img src when I hover on the button.

There are few answers that are 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>
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
Lee
  • 728
  • 7
  • 23

3 Answers3

8

You can do this using 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>
Super User
  • 9,448
  • 3
  • 31
  • 47
  • Thx! It worked by just using CSS! – Lee May 17 '17 at 07:06
  • Out of curiosity, what is the main difference between property "background" and "background-image"? – Lee May 17 '17 at 07:16
  • @Lee if you use `background-image` then you have to used `background-repeat`, `background-position` separate if you don't use exact size image which you are using in `width` & `height` tag – Super User May 17 '17 at 07:18
6

if you have new image source just use this code. use this method if you want change image with more than one 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');
});
Farsheed Feeruzy
  • 175
  • 1
  • 10
3

$(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>
athi
  • 1,683
  • 15
  • 26
  • This has 2 issues, **first** `$(this)` refers to `#Nav_Homepage` which is the button here not the image in it. **Second** you are only changing the image `src` on `mousover` and not changing it back to the original image when the mouse leaves – Mi-Creativity May 17 '17 at 06:57
  • 1
    Thanks! Have updated the code. – athi May 17 '17 at 07:01