shinya shinya - 12 days ago 8
Javascript Question

event.preventDefault not working. Ajax call causing this?

I'm trying to use scrolltop method and event.preventDefault is not working properly.
What I'm experiencing is that the page scrolls UP first then scrolls down.
It seems that The onclick causes the page to resubmit or something... (ajax post??)

I have following code

button (trigger)

<a id="nextset" class='nextbtn' >Next Step</a>


event

jQuery('#nextset').click(function (event) {
event.preventDefault();
movenext('set');
jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 2000);
});


functions

function getfav(obj) {
var myParams = "{ 'proattr':'" + obj + "'}";
jQuery.ajax({
type: "POST",
url: "project.aspx/getproject",
data: myParams,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () { jQuery('#wait').show(); },
complete: function () { jQuery('#wait').hide(); },
success: function (msg) {
GetProjectPic(msg.d, obj); //creates DOM and insert in div
Initbtns();// dynamic btns initialization
}
});
}

function movenext(obj) {
//other codes to hide/show DOM
getfav(nextobj);
}


If I add return faulse; in onclick event, the button doesn't work.

Any idea what's causing the scrolling to the top?

UPDATE:

It was caused by code block inside movenext function.

jQuery('[id^="favdiv"]').empty();


nothing to do with event.preventDefault.

The strange thing is that the screen scrolls much more than hidden div height ("favdiv") which causes up and down screen effect. I'm not sure how to prevent it...

UPDATE2

I searched jquery empty method and found this.

jquery "empty" changes the scrollbar

Answer

I end up writing something like this. still it goes up a bit but at least page doesn't jump

 jQuery('#favdiv' + obj).fadeOut('fast', function () { 
     jQuery('#favdiv' + obj).remove(); 
 });
 setTimeout(function () {
     jQuery('html,body').animate({ scrollTop: $('#subtitles').offset().top }, 1500);
 }, 500);