2

First I was looking at the onLoad event, but then when I read about it, I discovered that I was or going to be deprecated, so I search and found this info to use the on event to check if an image is loaded:load() method deprecated?

But the simple animation I will trigger, will not work. The element is not visible. It works if I reload the browser. The animation worked perfect until I added the load event. What could be wrong and how can I improve the code to work better?

    $("#intro-img").on("load", function() {

    $(".intro-content").animate({
    left: '20px',
    opacity: '1.0'
    });

});

EDIT: The script is running now after I used window instead of the id. Like this $(window).on("load", function() {.... Now the script should run when all content on the page has been loaded? But I guess there is never a guarantee that it will work 100% with images!?

Community
  • 1
  • 1
3D-kreativ
  • 9,053
  • 37
  • 102
  • 159

3 Answers3

2
$('#book').on("load",function(){
  //animate
});

Problem with this approach is when image is loaded from cache load event has a possibility that it is never triggered.When image is first downloaded jquery can have a chance to attach the event before image is loaded and work expected.But if image is loaded so quickly via cache then jquery may not have.

$('#book').on("load",function(){
  $(".intro-content").animate({
    left: '20px',
    opacity: '0.5',
    height:"300px"
    });
}).each(function(){
  if(this.complete) {
    $(this).trigger('load');
  }
});

This code attaches event and also checks whether image is already loaded and triggers the load event.

Mustafa ASAN
  • 3,747
  • 2
  • 23
  • 34
0

With $(window).load you must to wait to load all resources in web to execute script. You can make an image load event cross-browser. See this:

JavaScript/jQuery event listener on image load for all browsers

Instead of your code

 $('image').on('load')

You can use

 $('image').load()

Or attaching events with eventListener.

Good luck

Community
  • 1
  • 1
Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
0

Have you tried using the alternative JQuery function $(document).ready()?

  $( document ).ready(function() {
     $(".intro-content").animate({
         left: '20px',
         opacity: '1.0'
     });
  });
Meowsome
  • 99
  • 1
  • 10