1

I want to change image when user click on a thumb image, and prevent it to jump to the top of page.

the first code I wrote:

$('#photos-list img').click(function(e) {
    e.preventDefault();

    var imgObj = new Image();
    var targetObj = $('#main_image img');
    imgObj.onload = function() {
        targetObj.attr('src',this.src);

    }
    imgObj.src = $(this).attr('rel');
});

the preventDefault() works fine. ok, I want to add some effects to the image changing, like fade in, I add some jquery effects in

$('#photos-list img').click(function(e) {
    e.preventDefault();

    var imgObj = new Image();
    var targetObj = $('#main_image img');
    imgObj.onload = function() {
        targetObj.hide();
        targetObj.attr('src',this.src);
        targetObj.fadeIn('normal');

    }
    imgObj.src = $(this).attr('rel');
});

and this time , the preventDefault does not work, even I gave fadeIn() a preventdefault like:

targetObj.fadeIn('normal', function(e1){e1.preventDefault();});

any methods to solve this problem?

skargor
  • 1,011
  • 3
  • 15
  • 21

5 Answers5

4

try to end function with

return false;
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Peter Kaleta
  • 385
  • 3
  • 9
  • That is what prevenDefault does. It serves the same purpose. Must be an error somewhere – redsquare Aug 04 '09 at 23:56
  • 1
    it;s not exactly the same, see: http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false – Tim Jul 29 '10 at 13:57
2

You must be getting an error for the preventDefault to fail (although the js looks ok at first glance). Have you got firebug? Is that the exact source?

redsquare
  • 78,161
  • 20
  • 151
  • 159
0

You need to enable ie support.

Try the following:

$('#photos-list img').click(function(event) {
var ev = event || window.event;
ev.preventDefault();
// ... the rest of your code
Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
josedasilva
  • 290
  • 1
  • 7
0

The callback of the jQuery fadeIn function didn't receive an event parameter.

I asume you have the following structure:

<div id="#photos-list>
  <a href="#"><img src="..." /></a>
</div>

So try this:

$('#photos-list a').click(function(e) {
    e.preventDefault();
});
GiDo
  • 1,280
  • 12
  • 23
0

It's work:

if(event.preventDefault){
    event.preventDefault();
}else{
    event.returnValue = false; 
};
Stremlenye
  • 585
  • 1
  • 3
  • 15