Answer the question
In order to leave comments, you need to log in
Why does it scroll to the top of the page after ajax?
Hey guys, I can't figure it out.
After submitting a comment and receiving a successful ajax response, innerhtml happens but the page scrolls to the top.
I just found that it is necessary to set a fixed height for #notify, but this does not fit.
function pushComment() {
const comment_user = document.getElementById("comment_user").value;
const comment_data = document.getElementById("comment_data").value;
document.getElementById("notify").innerHTML = "";
if (comment_data.trim().length < 50) {
document.getElementById('notify').style.display = 'block';
document.getElementById('notify').style.background = '#c00';
const data = 'Сообщение слишком короткое';
//$('#notify').html(data);
notify.insertAdjacentHTML('afterbegin', 'Сообщение слишком короткое!<br>');
setTimeout(function(){
document.getElementById('notify').style.display = 'none';
}, 10000);
} else {
// ajax param
const data = {
comment_user: comment_user,
comment_data: comment_data,
};
$.ajax({
url: '/api/comments/push',
type: 'POST',
data: data,
success: function(data){
if (data.result == true) {
document.querySelectorAll('textarea').forEach(el=>el.value = '');
document.getElementById("notify").innerHTML = "";
document.getElementById('notify').style.display = 'block';
document.getElementById('notify').style.background = '#16a70e';
notify.insertAdjacentHTML('afterbegin', 'Ваш вопрос отправлен<br>Пожалуйста дождитесь ответа!<br>');
setTimeout(function(){
document.getElementById('notify').style.display = 'none';
}, 30000);
}
return false;
},
error: function(){
// return;
}
});
}
}
<div class="comments__data__form">
<form action="/api/comments/push" method="post">
<input type="hidden" id="comment_user" name="comment_user" value="48160">
<textarea name="comment_data" id="comment_data" rows="6" placeholder="Напишите ваш вопрос ..."></textarea><a href="#" onclick="pushComment()">Задать вопрос</a>
</form>
</div>
Answer the question
In order to leave comments, you need to log in
Add return false
at the end of the function.
Right now you don't override the default action on the link, so the link still follows href="#" , which causes it to scroll to the top of the page.
Well, for good, it would be necessary to use a normal button and listen to the submit event of the form.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question