Scroll up when you click on the pagination page - javascript

Can you please tell us how to make a scroll up when you click on the pagination page? There is a page of posts https://tvoidv.ru/culture/.
When you click on "Show more" (in itself) the page remains in place, but you need it to hide up or somehow it seems that the update has occurred. How can this be done?
Post loading code from json
$(document).on('click', '#more-news', function(e) {
e.preventDefault();
var _url = $(this).attr('data-url');
send = false; //убираем шумы
if (_url && !send) {
$.ajax({
url: _url,
type: 'GET',
dataType: 'json',
beforeSend: function() {
// включение прелоудера
send = false;
},
complete: function() {
// отключение прелоудера
},
success: function(obj) {
send = true;
$('#more-news').remove(); //удаляем текущю кнопку
$("#get_news").append(obj['html'])//добавляе готвую разметку
if('show_more' == true){
$('#more-news').show();
} else {
$('#more-news').hide();
} //добавляем кнопку если пришел флаг
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText + "\r\n" + xhr);
}
});
}
});

I cannot see your HTML, so assuming that #more-news is where you would want to dock to
Add this to the success block after the element is visible
var element = $('#more-news').get(0)
element.scrollIntoView({behavior: "smooth", block: "end", inline: "nearest"});
More options here - https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Smooth behavior is limited to certain browsers.

Related

AJAX sending multiple requests after button click

I just want one click to equal one submit in my jQuery code.
I've read quite a few posts on this same topic but I think mine is different. I do have a mouseleave and focusout event that I'm using to find errors in user input. Those functions feed down into the function that is submitting multiple times. The more times I hit mouseleave and focusout the more times my Ajax request is submitted. But I need mouseleave and focusout to continue to work and check the users input, that's why I'm not using one. Please see my code below, the function that I think is submitting multiple times is handleButtonClicksAfterError
function getCreditAmountToSend(modal){
console.log("getCreditAmountToSend");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
checkBox.change(function(){
if($(checkBox).is(":checked")) {
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('amountToSend', creditAmount);
}
});
var pendingCreditAmount = $(modal).contents().find("#pending_credit_amount");
pendingCreditAmount.on({
mouseleave: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
},
focusout: function(){
if(pendingCreditAmount.val() != ""){
adminForGetPendingCredit(modal);
}
}
});
}
function adminForGetPendingCredit(modal){
console.log("adminForGetPendingCredit");
var checkBox = $(modal).contents().find("#fresh-credit-checkbox");
if(!$(checkBox).is(":checked")) {
var enteredAmount = +($(modal).contents().find("#pending_credit_amount").val());
var creditAmount = +(sessionStorage.getItem("creditAmount"));
sessionStorage.setItem('enteredAmount', enteredAmount);
doWeDisplayError(modal,creditAmount, enteredAmount);
}
}
function doWeDisplayError(modal,creditAmount, enteredAmount){
console.log("doWeDisplayError");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", false);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", false);
if(creditAmount < enteredAmount){
$(modal).contents().find("#pending_credit_amount").val("");
$(modal).contents().find("#fresh-credit-continue-shopping").prop("disabled", true);
$(modal).contents().find("#fresh-credit-checkout").prop("disabled", true);
displayError();
}
else{
handleButtonClicksAfterError(modal, enteredAmount);
}
}
function handleButtonClicksAfterError(modal, enteredAmount){
// this is the problem!!!!!!!!!!!!!
console.log("handleButtonClicksAfterError");
sessionStorage.setItem('amountToSend', enteredAmount);
var continueButton = $(modal).contents().find("#fresh-credit-continue-shopping");
continueButton.click(function() {
modal.hide();
});
var checkoutButton = $(modal).contents().find("#fresh-credit-checkout");
checkoutButton.click(function() {
console.log("handleButtonClicksAfterError");
sendData();
});
}
function displayError(){
console.log("displayError");
$(function(){
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr("placeholder", "Whoops, that was too much");
$("#fresh-credit-iframe").contents().find("#pending_credit_amount").attr({
class: "form-control form-control-red"
});
sessionStorage.removeItem('enteredAmount');
});
}
This is the function that actually POSTs the data
function sendData(){
var amountToSend = sessionStorage.getItem("amountToSend");
var products = $.parseJSON(sessionStorage.getItem("products"));
console.log("sendData");
console.log("This is the amount to send " + amountToSend);
$.ajax({
url: "/apps/proxy/return_draft_order",
data: {amountToSend, products},
type: "POST",
dataType: "json",
complete: function(data) {
window.location.href = data.responseText;
console.log("This is the URL from poll " + data.responseText );
return false;
},
});
}
It ended up being super simple.. I just needed the jQuery off method.. I attached it to the button before click and everything is peachy.. Looks like this:
checkoutButton.off().click(function(){});
off clears all the previous event handlers and then just proceeds with Click
Pretty cool, to read more check it out here
use async:false to prevent multiple request
$(document).off('click').on('click', function(){
$.ajax({
type:'POST',
url: ,
async:false,
cache: false,
data:{}
,
success: function(data){
},
error:function(data){
}
});
});

autofocus(autotab) on next element is not working for dynamically created fields

$("#destination1" + countVar).autocomplete({
minLength : 3,
source : function(request, response) {
var url = configOptions.icaocodeUrl;
var term = request.term;
url=url+term;
console.log(url);
$.ajax({
url : url,
type : "GET",
data : request,
dataType : "json",
success : function(data) {
response(data.slice(0, 10));
//alert(data);
},error: function(xhr, textStatus) {
alert('error');
}
});
},
change:function(event,ui){
console.log("fired in dest2");
},close:function(event,ui){
console.log("close in dest2"+'#dof1'+countVar);
console.log(countVar);
$(this).parents('form').find('#dof1'+countVar)
.filter(function () { return $(this).val() === ''; })
.first().focus();
}
});
above is my code for autocomplete and autotab(autofocus) to next field for dynamically created elements.autotab(autofocus ) is working fine for normal html but it is not working for dynamically created elements only.
Are you trying to focus() on a tab that is being dynamically added? If so, you might be triggering focus() to soon and the DOM element might not be there.
Try wrapping the focus function into a setTimeout() function to test it out.
setTimeout(function () {
$(this).parents('form').find('#dof1'+countVar)
.filter(function () { return $(this).val() === ''; })
.first().focus();
}, 2000); // 2 seconds

setTimeOut/setInterval runs just once

I use function App.loadTo to load some data in any place. I need a delay before displaying any content (used form-styler plugin, redrawing form). I tried setTimeout and setInterval functions, but they run just once, i.e.
1) Called App.loadTo( params ) - delay works
2) Called App.loadTo( params ) with the same params - delay doesnt work
I tried the following with no success
tmp = setInterval(function() {
console.log('I show all invisible!', params.where);
$(params.where).css({
'visibility': 'visible'
});
$('#preloader').remove();
clearInterval(tmp);
}, 110);
Where did I make a mistake?
App.loadTo = function loadTo(params) {
$.ajax({
url: '/' + params.controller + '/' + params.action + '',
type: 'POST',
dataType: 'json',
data: params.sentData,
success: function(server_answer, textStatus) {
if (server_answer.result == 'success') {
if (params.hasOwnProperty('parseHtml')) {
// Data parsing
var html = $(server_answer.html);
html = $(html).find(params.parseBlock);
} else {
var html = $(server_answer.html);
}
// Inserting data
$(params.where).empty().html(html).css({
'visibility': 'hidden'
}).before('<div id="preloader" style="width: 100%; background: url("i/preloader.gif") no-repeat scroll 50% center transparent; min-height: 140px; height: 100%;"></div>');
// Delay before display
setTimeout(function() {
console.log('I show all invisible!', params.where);
$(params.where).css({
'visibility': 'visible'
});
$('#preloader').remove();
}, 110);
} else {
alert_jq_ui(server_answer.error_txt);
}
},
error: function(xhr, errmsg, err) {
alert_jq_ui(xhr, errmsg, err);
}
});
};
Try clearing the setTimeout with clearTimeout(); if you choose to go with that, else if you rather want to try the setinterval method, try clearing it outside of itself, i hope this helps
I created a little fiddle, stripped down your code ... http://jsfiddle.net/gnsnvjtz/
The big difference here is this:
var App = {
loadTo: function () {
///loadTo code goes here ...
}
}
instead of `App.loadTo = function loadTo(params) ...

JQuery message should delay() and fadeOut()

I am using the following script with a contact form, however I need to have a small modification and can not figure out how to achieve this.
As it is at the moment the #note message slides open and stays open.First off all I will change the .slideUp to fadeIn, and then I would need to close the message after a couple a seconds, so I suppose I should to add .delay(2000).fadeOut() but I don't understand how to implement this changes. Thank you
The jQuery
var close_note = $("#note");
close_note.click(function () {
jQuery("#note").slideUp(1000, function () {
jQuery(this).hide();
});
});
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="images/ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(1000, function() {
$(this).hide();
});
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
if(msg === 'OK') { $("#ajax-contact- form").find('input, textarea').val(""); }
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Your message has been sent. Thank you!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(1000);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
You can use something like this to do show the #note for a few seconds, then fade it out
$('#note').hide().html(msg).fadeIn(1000, function() {
$(this).delay(3000).fadeOut(1000);
});
So the code would look like
$("#ajax-contact-form").on('submit', function() {
$('#load').append('<center><img src="images/ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
$.ajax({
type: "POST",
url: "contact.php",
data: $(this).serialize()
}).done(function(msg) {
$('#loading').fadeOut(300, function() {
$(this).remove();
if(msg === 'OK') {
$("#ajax-contact-form").find('input, textarea').val("");
msg = '<div class="success">Your message has been sent. Thank you!</div>';
}
$('#note').hide().html(msg).fadeIn(1000, function() {
$(this).delay(3000).fadeOut(1000);
});
});
});
return false;
});

Activate jquery Ajax on click on list and pull number

This is my code that I have built from several different pieces of information online:
http://jsfiddle.net/spadez/qKyNL/6/
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
// Fadeout the existing content
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
// Scroll to top
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
// Fade in content
$('#content').fadeTo(500, 1);
},
});
My question is, how do I trigger the ajax request from clicking on one of the pagination list links (like 1 or 2) whilst using e.prevent default so it is degradable (it will still work if JavaScript is disabled). I guess what I am trying to do is the following in pseudo code:
Listen for a click of the pagination link
Grab the number of the link clicked (ie was 1 or 2 clicked)
try
$('a').click(function(){
var number = $(this).attr('href');//get the pg=1 value on the href
alert(number);
//ajax here
});
I'm not sure I completely understand your question, however something like this should work:
$(function() {
var clicks = {};
var sendAjax = function(href) {
//do something with href
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
// Fadeout the existing content
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
// Scroll to top
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
// TO DO: Set number as active class
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
// Fade in content
$('#content').fadeTo(500, 1);
},
});
};
$('a').click(function() {
var href = $(this).attr('href');
clicks[href] = clicks[href] ? clicks[href] + 1 : 1;
sendAjax(href);
return false; //disable the link
});
});
can't you just set an onclick on those link 1 and link 2?
ex:
link1.click(function() {
// do stuff with the ajax
});

Categories

Resources