Can't fade in an image loaded with jquery

35 Views Asked by At

I'm a novice at jQuery and I don't understand why the image displays, but it doesn't fade in as the jQuery documentation suggests.

<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta charset="UTF-8">
<title>slide show test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<img id="image" alt="slide" style="opacity:0.5;"/>
<script>
var x="tiananmen-square-600.webp";
$("#image").attr('src', x, function() {
        $("#image").fadeIn( "slow");
        });
</script>
</body>
</html>

Help, please.

2

There are 2 best solutions below

0
Phil On

.attr() doesn't accept a 3rd parameter.

I think you want something like this

const x = "https://picsum.photos/200/300";

const image = $("#image").hide().attr("src", x);

image[0].decode().then(() => {
  image.fadeIn("slow");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="image" />

That is

  1. Select the #image element
  2. Initially hide it
  3. Set it's src attribute
  4. Wait for the image data to become available (see decode())
  5. Fade it in
0
Ed S. On

I got it to work by removing the opaque styling in the img tag and replacing the jQuery code with this:

$("#image").fadeOut(0);
$("#image").attr('src', x);
$("#image").fadeIn("slow");