简体   繁体   中英

jQuery random fade in and out with hover

I got some help with jQuery for a fade in and out, but it's not quite working the way I need it to. This is the script:

$(document).ready(function(){
  $("#trivlimp").hover(function(){
    $("#trivlimp").fadeToggle("slow");
    $("#imp").fadeToggle("slow");
  });
});

Instead of just showing the content like I want it to, it keeps fading in and out when I hover over 'trivlimp' instead of just showing the content of 'imp' and then fading out when I stop hovering. You can see an example of what I'm trying to say here when you hover over the mini-profile on the left. http://trivli.b1.jcink.com/index.php?showtopic=2&st=0&#entry2

Pu them bot inside a container put the hover effect on the container and then show hide the children.

Sample: http://jsfiddle.net/TX4g5/6/

Code: JS

$(document).ready(function(){
  $("#wrapper").hover(function(){
    $("#wrapper p:first-child").fadeToggle("slow");    
$("#wrapper p:last-child").fadeToggle("slow");

  });
});​

HTML:

<div id="wrapper">
    <p>Normal visible</p>
    <p style="display:none">Visble when hovered</p>
</div>​

CSS:

/*CSS so  both p elements are above each other*/
#wrapper {
    position: relative;
}
#wrapper p{
    position: absolute;
    top: 0;
    left: 0;
}

It is actually normal behaviour:

You use the hover function to hide the the #trivlimp. It fades nicely, but when it is completely faded out you hover "out" the element and the fadetoggle is toggled to fade again. this time it wil fade in. because it is faded in, you hover the element again and it is faded out and so on...

Try to add classes with display settings like hidden, none, block or inline when de fade has completed.

$("#trivlimp").fadeToggle("slow").addclass("hidden");
$("#imp").fadeToggle("slow").addclass("visible);

personally I don't think this is the best practice... I would recommend using mouseOver and mouse out to toggle effects and add/remove classes yourself.

$("#wrapper").mouseover(function() {
    $("#trivlimp").fadeOut("slow");
    $("#imp").fadeIn("slow");
}).mouseout(function() {
    $("#trivlimp").fadeIn("slow");
    $("#imp").fadeOut("slow");
});

This way you have a lot more control over what you are doing (ok, it requires a little more typing, but the result is the most important...)

*edit: I'm sorry, I wasn't thinking too straight, you must add a wrapper around it, because the code i wrote will give the same result as yours...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM