0

Ok i have some jquery javascript which i intend on adding a .load() event to, hopefully someone can assist me.

$(function() {

  $('#nav li a img').each(function() {
   var originalSrc = this.src,
       hoverSrc = originalSrc.replace(/\.(gif|png|jpe?g)$/, '_over.$1'); 
       image = new Image();

   image.src = hoverSrc;

   $(this).hover(function() {
      this.src = hoverSrc;
   }, function() {
      this.src = originalSrc;
   });
  });
})
5
  • Have you had a look at the documentation? There are examples: api.jquery.com/load-event Commented Apr 27, 2011 at 6:57
  • Yes, don't worry this is somewhat between alex and me. Commented Apr 27, 2011 at 6:59
  • It's not fair to say that because Stack Overflow questions can be commented/answered by anyone. @Felix I have been commenting a bit with @Jason helping him with jQuery and image loading in his previous questions. Commented Apr 27, 2011 at 7:02
  • @alex, @Jason: No worries :) Good work @alex! Commented Apr 27, 2011 at 7:16
  • @alex i understand i just couldn't think how to explain it which you did perfectly Thank you @alex @felix. @alex i have also made one final question for you which i would love you to help me with stackoverflow.com/questions/5800739/… Commented Apr 27, 2011 at 7:24

1 Answer 1

2

Before you set the src property of the Image, attach the callback like so...

image.onload = function() {
  // The image has loaded successfully.
}

When the image has loaded and is successful, it will call that function.

If the function is not successful, it will call the function assigned to the onerror property.

Alternatively, you can use $(image).load(function() { ... }).

Sign up to request clarification or add additional context in comments.

4 Comments

Did you edit my post after i posted it? I actually did it right after i edited it. So where does this go in my/your code.
is it correct i simply place the previous code inside the { }
@Jason Place it before you set the src property, but after you have instantiated image. So place it immediately before the image.src = hoverSrc; line.
was just reading about callbacks so i sort of understand now :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.