Somenath Sinha Somenath Sinha - 4 months ago 8
Javascript Question

Why isn't fadeIn() working?

My HTML Code is :

<!DOCTYPE html>
<html>
<head>
<title>Furry Friends Campaign</title>
<link rel="stylesheet" type="text/css" href="styles/my_style.css">
</head>
<body>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
<img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#clickMe").click(function()
{
$("img").fadeIn(1000);
$("#picframe").slideToggle("slow");
});
});
</script>
</body>
</html>


The accompanying CSS looks like:

#clickMe {
background: #D8B36E;
padding: 20px;
text-align: center;
width: 205px;
display: block;
border: 2px solid #000;
}

#picframe {
background: #D8B36E;
padding: 20px;
width: 205px;
display: none;
border: 2px solid #000;
}


The slideToggle works perfectly, but for some reason, the image doesn't fade in. I've tried setting the duration to longer periods, but that yields the same results. Can someone point out what's wrong with this code? I'm using the latest version of Chrome.

UPDATE: I tried running the example code of the book I was using, which uses
jquery-1.6.2.min.js
and using that version of jQuery, the code works perfectly. Is this some error on jQuery's part? Or is the new way that things will be done now?

Answer

Since jQuery 1.8, fadeIn no longer initially hides the image, so trying to fade in an image which is visible or doesn't have display set to none won't lead to anything.

To fade in, you should hide it first. Initially it's not hidden, since children don't inherit display CSS property, and you have set it to none only on #picframe, the parent of img. Just add $("img").hide(); on ready. This will make it work.

Since it looks like you need to fade it in / out with each click, you could do the following instead of $("img").fadeIn(1000):

if($("img").is(":hidden")) $("img").fadeIn(1000);
                      else $("img").fadeOut(1000);

Demo below.

#clickMe {
  background: #D8B36E;
  padding: 20px;
  text-align: center;
  width: 205px;
  display: block;
  border: 2px solid #000;
}
#picframe {
  background: #D8B36E;
  padding: 20px;
  width: 205px;
  display: none;
  border: 2px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="clickMe">Show me the the Furry Friend of the Day</div>
<div id="picframe">
  <img src="images/furry_friend.jpg" alt="Our Furry Friend">
</div>
<script type="text/javascript" src="scripts/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    //$("img").hide();
    $("#clickMe").click(function() {
      $("img").fadeIn(1000);
      $("#picframe").slideToggle("slow");
    });
  });
</script>

Comments