ammcom
ammcom

Reputation: 1034

JQuery - show hide button when mouse enter / leave an image

In my web page I have an image that has a button positioned over it. I want to show and hide the button as mouse enter and leave the image:

$('#UserImage').mouseenter(function()
    {
        $('#ButtonChange').show();
    }).mouseout(function()
    {
        $('#ButtonChange').hide();
    })

It is working but as the button is contained inside the image when the mouse enters the button it is considered to leave the image so the button is hidden then at tha same moment as the button is hidden the mouseenter event is triggered again and the button is shown causing a flickering effect

any suggestion to solve this?

Edit:

$('#UserImage').mouseenter(function() {
  $('#ButtonChange').show();
}).mouseout(function() {
  $('#ButtonChange').hide();
})
.imageUser {
  width: 150px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="position:relative;width=150px">
  <img ID="UserImage" class="imageUser" ImageUrl="~/Images/logo.jpg" />
  <input type="button" ID="ButtonChange" Text="Change" style="position: absolute;top: 180px;height:25px;left:0px;width:100px;display:none">
</div>

Upvotes: 2

Views: 2297

Answers (4)

Deepak Yadav
Deepak Yadav

Reputation: 7069

The whole thing is also possible with pure CSS ! for such simple thing, you don't really need Jquery !

.imageUser {
  width: 150px;
  height: 200px;
}
.img-wrapper {
  position: relative;
  width: 150px
}
.img-btn {
  position: absolute;
  top: 180px;
  height: 25px;
  left: 0px;
  right:0; /* gave right, to align the button in center */
  margin:0 auto; /* as button as fixed width, margin aligns in center */
  width: 100px;
  display: none
}
.img-wrapper:hover .img-btn {display:block} /* whenever mouse hovers the image wrapper, the button is shown, other time, its hidden */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="img-wrapper">
  <img ID="UserImage" class="imageUser" ImageUrl="~/Images/logo.jpg" />
  <input type="button" ID="ButtonChange" Text="Change" class="img-btn">
</div>

Upvotes: 3

NKD
NKD

Reputation: 1049

Try hover?

$("#UserImage").hover(function () {
    $('#ButtonChange').show();
}, function () {
    $('#ButtonChange').hide();
});

I don't have an image so I make a div instead. See Fiddle below.

Fiddle: https://jsfiddle.net/9koswww1/1

Upvotes: 1

Payer Ahammed
Payer Ahammed

Reputation: 907

try this

$('#UserImage').mouseenter(function()
{
    $('#ButtonChange').show();
}).mouseleave(function()
{
    $('#ButtonChange').hide();
})

Upvotes: 0

Lukas Froehlich
Lukas Froehlich

Reputation: 19

Change mouseenter to mouseover.

https://api.jquery.com/mouseenter/ Check the bottom of the page for an example.

Upvotes: 0

Related Questions