JQuery animation makes page jump to top

776 Views Asked by At

I found a bit of script to make a div loginform slide in from the edge of the back, and back out, on different clicks, of loginshow and loginhide. Also a bit of script to make topbar (containing the 'show' button) and loginform to scroll down when I scroll down the page.

My intent is for loginform to be hidden and shown from anywhere, so you do not have to scroll to the top of the page to access the fields/elements on that div.

However whenever I click loginshow or loginhide, the page jumps back to the top as the loginform animation runs.

This is the script

var main = function() {
$('#loginshow').click(function(){
    $('#topbar').animate({
        left: '245px'
    }, 200);
    $('#loginform').delay(100).animate({
        left: '0px'
    }, 200);    
    $('#loginhide').delay(200).animate({
        left: '0px'
    }, 100);
});
$('#loginhide').click(function(){
    $('#loginhide').animate({
        left: '-80px'
    }, 200)
    $('#loginform').delay(200).animate({
        left: '-240px'
    }, 200)
    $('#topbar').delay(300).animate({
        left: '5px'
    }, 200);
})
$(window).on('scroll', function () {
    var scrollPos = $(document).scrollTop();
    $('#loginform').css({
        top: scrollPos
    });
    $('#topbar').css({
        top: scrollPos
    });
}).scroll();
};
$(document).ready(main);

How can I stop the loginshow and loginhide functions make the page jump back up? Thanks for any help, I have only just started with javascript yesterday.

1

There are 1 best solutions below

2
On BEST ANSWER

Did you tried using jQuery preventDefault()?

    $('#loginshow').click(function(event){
        event.preventDefault();
// Your code here
    });