skargor
skargor

Reputation: 1031

jquery prevent default does not work

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?

Upvotes: 1

Views: 7689

Answers (5)

Peter Kaleta
Peter Kaleta

Reputation: 385

try to end function with

return false;

Upvotes: 4

josedasilva
josedasilva

Reputation: 290

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

Upvotes: 0

Stremlenye
Stremlenye

Reputation: 595

It's work:

if(event.preventDefault){
    event.preventDefault();
}else{
    event.returnValue = false; 
};

Upvotes: 0

GiDo
GiDo

Reputation: 1340

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();
});

Upvotes: 0

redsquare
redsquare

Reputation: 78677

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?

Upvotes: 2

Related Questions