sizz sizz - 4 months ago 7
HTML Question

Why does my page go up after every post

var main = function(){
$('.btn').click(function() {
var post = $('.status-box').val();
$('<li>').text(post).prependTo('.posts');
$('.status-box').val('');
$('.counter').text('140');
$('.btn').addClass('disabled');
});
$('.status-box').keyup(function(){
var postLength = $(this).val().length;
var charactersLeft = 140 - postLength;
$('.counter').text(charactersLeft);
if (charactersLeft < 0){
$('.btn').addClass('disabled');
}
else if (charactersLeft == 140){
$('.btn').addClass('disabled');
}
else {
$('.btn').removeClass('disabled');
}
});
$('.btn').addClass('disabled');
};

$(document).ready(main);


My page keeps going to the top every time I make a post any ideas of why this would be happening? I have a div with an option to make a 140 character post that gets put into a list and display on the page. Every time I make one of these posts the webpage goes up to the top and to see the post you must scroll all the way back down.

Answer

Most likely, the default form submission or link following behavior is executing in addition to your custom event logic. It's probably navigating to # or some other anchor near the top of your page. To prevent that from happening change

$('.btn').click(function() {
    ...

to

$('.btn').click(function(event) {
    event.preventDefault();
    ...