Home > Mobile >  How do I get this jQuery fade in function working?
How do I get this jQuery fade in function working?

Time:03-15

I'm trying to get this background image to fade in when the page loads.

I've tried selecting the image by class and used the fadeIn() method but nothing is happening when loading the screen?

Am I missing something?

// document.ready(alert("Welcome!"));

$(".background").ready(function () {
  $(".background").fadeIn("slow");
});

Above is the jQuery I've been trying.

And here is the html for reference:

<body>
    <img  src="restaurant.jpg" />
</body>
   
  

Thanks! Im also brand new to jQuery just learning..

CodePudding user response:

You need to set your image display: none; initially

<img  src="restaurant.jpg" style="display: none;"/>

And then you can call this in your Javascript

$(".background").ready(function () {
  $(".background").fadeIn("slow");
});

Or like this

$(document).ready(function() {
  $(".background").fadeIn("slow");
});

CodePudding user response:

// Alternative to load event
    document.onreadystatechange = function () {
      if (document.readyState === 'complete') {
    alert('Dom loaded');
        $(".download").fadeIn();
      }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src='https://www.w3schools.com/images/compatible_chrome.png' class='download' style='display:none;'>

First hide the image then Try the below code which executes once dom loaded.

// Alternative to load event
document.onreadystatechange = function () {
  if (document.readyState === 'complete') {
    console.log('loaded');
    $(".background").fadeIn("slow");
  }
}

CodePudding user response:

  1. set display none
  2. Set milliseconds timeout in fadeIn.

$(document).ready(function() {
  $('.background').css("display", "none").fadeIn(5000); // 5 Second
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img  src="https://picsum.photos/200/300"/>

  • Related