Priyanka Maurya Priyanka Maurya - 5 months ago 26
jQuery Question

Fadein, Fadeout events together using jquery

I want fade in fade out event work separately for all the div but when my mouse enters first div it effect all other div.If I do not define demo and demo1 function separately then its working fine otherwise its working like this.I do not understand what is wrong?

<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<p>Fade Out Example</p><br>
<div class="fade" id="div1" style="background-color:red;width:100px; height:100px"> </div><br>
<div class="fade" id="div2" style="background-color:blue;width:100px; height:100px"> </div><br>
<div class="fade" id="div3" style="background-color:cyan;width:100px; height:100px"> </div>

</body>

<script>

$(document).ready(function(){
$("#div1").bind("mouseenter",(demo));
$("#div1").bind("mouseleave",(demo1));

$("#div2").bind("mouseenter",(demo));
$("#div2").bind("mouseleave",(demo1));

$("#div3").bind("mouseenter",(demo));
$("#div3").bind("mouseleave",(demo1));
});
function demo()
{
$("#div1").css("background-color","lightgreen").fadeOut();
$("#div2").fadeOut();
$("#div3").fadeOut();
}
function demo1(){
$("#div1").css("background-color","red").fadeIn();
$("#div2").fadeIn();
$("#div3").fadeIn();
}
</script>
</html>

Answer

use fadeTo which will not remove the div element in your DOM; run it in code snippet

    function demo(id)
    {
        if(id == 1){
            $("#div"+id).css("background-color","lightgreen").fadeTo('slow',0);
        }else if(id != 1){
            $("#div"+id).fadeTo('slow',0);
        }
    }
    function demo1(id){
        if(id == 1){
            $("#div"+id).css("background-color","red").fadeTo('slow',1);
        }else if(id != 1){
            $("#div"+id).fadeTo('slow',1);
        }
    }
<style>
    .fade{display: block;}
</style>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<p>Fade Out Example</p><br>
<div class="fade" id="div1" style="background-color:red;width:100px; height:100px" onmouseover="demo('1');" onmouseout="demo1('1')"> </div><br>
<div class="fade" id="div2" style="background-color:blue;width:100px; height:100px" onmouseover="demo('2');" onmouseout="demo1('2')"> </div><br>
<div class="fade" id="div3" style="background-color:cyan;width:100px; height:100px" onmouseover="demo('3');" onmouseout="demo1('3')"> </div>

</body>


</html>