shinya shinya - 8 months ago 44
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>


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


function getfav(obj) {
var myParams = "{ 'proattr':'" + obj + "'}";
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

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

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


It was caused by code block inside movenext function.


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...


I searched jquery empty method and found this.

jquery "empty" changes the scrollbar

Answer Source

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