I have a problem with jQuery. I am trying to make an image appear(or fade in) upon onmouseover event and disappear(or fade out) upon onmouseout event. The HTML that I have is:
<div class="wrapper">
<img id="mainImg" src="..." />
</div>
The CSS:
#mainImg
{
visibility:hidden;
}
And the JavaScript is as follows:
$("#mainImg").mouseover(function () {
$(this).attr("visibility", "visible");
}).mouseout( function () {
$(this).attr("visibility", "hidden");
});
But this code does not work. I am struggling to understand what is wrong but I cannot sort it out. I tested the code also in JsFiddle with no result. I also tried with the hover() function without success.
May you please tell me what I am doing wrong and propose a solution? Thanks
Francesco
I have a problem with jQuery. I am trying to make an image appear(or fade in) upon onmouseover event and disappear(or fade out) upon onmouseout event. The HTML that I have is:
<div class="wrapper">
<img id="mainImg" src="..." />
</div>
The CSS:
#mainImg
{
visibility:hidden;
}
And the JavaScript is as follows:
$("#mainImg").mouseover(function () {
$(this).attr("visibility", "visible");
}).mouseout( function () {
$(this).attr("visibility", "hidden");
});
But this code does not work. I am struggling to understand what is wrong but I cannot sort it out. I tested the code also in JsFiddle with no result. I also tried with the hover() function without success.
May you please tell me what I am doing wrong and propose a solution? Thanks
Francesco
Share Improve this question asked Apr 27, 2011 at 9:17 CiccioMiamiCiccioMiami 8,26634 gold badges96 silver badges158 bronze badges 1-
You could also use
hover(function() { //onmouseover }, function() { //onmouseout });
– Sylvain Commented Apr 27, 2011 at 9:25
3 Answers
Reset to default 8Visibility is not an HTML attribute; it's a CSS feature. Try using css() instead of attr().
Find working sample here: http://jsfiddle/ezmilhouse/MegL9/1/
you will run into problems if triggering events on invisible elements, better attach event to .wrapper:
your js:
$(".wrapper").mouseover(function () {
$('img', this).css("visibility", "visible");
});
$(".wrapper").mouseout(function () {
$('img', this).css("visibility", "hidden");
});
your html:
<div class="wrapper">
<img id="mainImg" src="http://www.google./images/logos/ps_logo2.png" />
</div>
Actually the correct way to do that is using .toggle() function. Something like this:
$("#mainImg").mouseover(function () {
$(this).toggle();
}).mouseout( function () {
$(this).toggle();
});
Or using .hide() / .show(), like this:
$("#mainImg").mouseover(function () {
$(this).hide();
}).mouseout( function () {
$(this).show();
});
The cool thing about doing it this way is that you can specify animations for the visible / invisible transitions.
Cheers!