I've done AJAX post loaders before but I'm having quite an hard time with jScrollPane.
Two things:
where should I load the posts? the div i created (#reviewspostscont) or .jspPane that JScrollPane makes? what if i have multiple loops then?
a more practical one now, this is the code i have so far, I can't get the function that triggers the AJAX to get the isAtRight variable (undefined in console), any fix?
Thanks in advance, Matt
$(function() {
$('#reviewspostscont').each(function() {
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight) {
console.log('Handle jsp-scroll-x', this,
'scrollPositionX=', scrollPositionX,
'isAtLeft=', isAtLeft,
'isAtRight=', isAtRight);
}
);
$(this).jScrollPane({ horizontalDragMaxWidth: 100 });
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind('resize', function() {
if (!throttleTimeout) {
throttleTimeout = setTimeout(function() {
api.reinitialise();
throttleTimeout = null;
}, 50);
}
});
});
$('#reviewspostscont').scroll(function() {
var $this = $(this);
var scrollWidth = $this[0].scrollWidth - $this.width();
var scrollPercentage = $this.scrollLeft() / scrollWidth * 100;
if (isAtRight == true) {
loadArticle(count);
count++;
}
});
function loadArticle(pageNumber) {
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop',
success: function(html) {
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});
Related
Struggling to get this to work properly...Making an if/else statement with setInterval that if class is clicked, content refreshes, else content auto refreshes after a specific time period. This is what I have for just auto refreshing atm (which works perfectly):
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
What I've tried to get a "click" function added, but doesn't do anything...:
$('.contentTwoClicked').on('click', function() {
var refreshClicked = true;
if(refreshClicked) {
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
} else {
var auto_refreshContentTwo = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000
);
}
});
Where am I going wrong? Or am I way off-base here...? Any guidance/help would be greatly appreciated!
You don't need a conditional statement, but rather a variable to store the set interval in so that it can be cleared and restarted on manual refresh via a calling function:
//variable to store the setInterval
let refreshInterval = '';
//function that calls setInterval
const autoRefresh = () => {
refreshInterval = setInterval(()=> {
refresh();
console.log("auto");
},3000)
}
//run setInterval function on page load;
autoRefresh();
//manual refresh function
const manualRefresh = () => {
//erases the setInterval variable
clearInterval(refreshInterval);
refresh();
//then recalls it to reset the countdown
autoRefresh();
console.log("manual");
}
//for visual purposes
let refreshCount = 0;
//node refresher function
const refresh = () => {
const container = document.getElementById("refresh");
refreshCount ++;
container.textContent= "This div will be refreshed"+ ` Refresh Count: ${refreshCount}`;
}
<button onclick="manualRefresh()">Click to Refresh </button>
<div id="refresh">This div will be refreshed</div>
See it in action: https://codepen.io/PavlosKaralis/pen/rNxzZjj?editors=1111
Edit: Applied to your code I think it would be:
let interval;
var autoRefresh = () => {
interval = setInterval (
function() {
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
}, 495000);
}
$('.contentTwoClicked').on('click', function() {
clearInterval(interval);
alert('clicked');
$('.page_loading_r_content_two_overlay').fadeIn();
$.ajax({
url: '../../path/to/page.php',
success: function(html) {
var myContentTwoContent = $('#refreshContentTwo').html(html).find('#refreshContentTwo2');
$('#refreshContentTwo').html(myContentTwoContent);
}
});
autoRefresh();
});
autoRefresh();
my admin-ajax.php file is causing quite a bit of server load and ending up with a 400 request. Ive honed in on the culprit which appears to be "action=wishlist_counter" caused by woocommerce. Although the cart is disabled its still causing issues. The code in question is found in my themes custom.js file and appears as is below;
/*************************************************************
WOOCOMMERCE WISHLIST
*************************************************************/
function to_wishlist_count() {
$.ajax({
type: 'POST',
url: to_ajaxurl,
data: {action : 'wishlist_counter'},
success:function(data) {
$('.to-wishlist-number').html(data);
if(parseInt(data) === 0 ) {
$('.to-wishlist-counter').animate({top:'-100%'}, 0);
} else {
$('.to-wishlist-counter').animate({top:0}, 400);
}
}
});
}
$(document).ready(function() {
to_wishlist_count();
});
$(document).on('click', '.product-remove a', function() {
setTimeout(function() {
to_wishlist_count();
}, 1500);
});
$(document).on('click', '.add_to_wishlist', function(){
var $this = $(this);
var productAdded = $this.parents('li.product').find('h3').text();
if (productAdded == '') {
productAdded = $('h1').text();
}
$('.wishlist-notification .item-product').html('"'+productAdded+'"');
$this.parents('li.product').find('.product-img-wrap div.loading').fadeIn(100);
setTimeout(function(){
$('.to-wishlist-number').html(parseInt($('.to-wishlist-number').html())+1);
$this.parents('li.product').find('.product-img-wrap div.loading').fadeOut(100);
$('#header .wishlist-notification').fadeIn(400);
setTimeout(function(){
to_wishlist_count();
$('#header .wishlist-notification').fadeOut(400);
},2250);
},500);
});
})(jQuery);
What would be the best way of removing this code or ceasing it from its dastardly activities. Removing it from the file? or perhaps a function of sorts?
I want to use preventDefault() in .each function for collection of buttons and its not working. When I use it with one .click function it works fine but inside .each is not
Whan am I doing wrong?
Here is my .js code
$(document).ready(function() {
var findingStatus = $('#findingStatus').attr('finding-status-type');
var findingLike = $('#finding_like_btn');
var findingDislikeBox = $('.finding_dislike_add');
var findingDislikeCollection = $('.finding_dislike_add_btn')
var findingUnlike = $('#finding_unlike_btn');
var findingDislikeRemoved = $('#finding_dislike_removed');
var alertBox = $('.alert-box').hide();
if (findingStatus == 0) {
findingDislikeBox.show();
findingUnlike.hide();
findingDislikeRemoved.hide();
}
else if (findingStatus == 1) {
findingDislikeBox.hide();
findingUnlike.show();
findingDislikeRemoved.hide();
}
else if (findingStatus == 2) {
findingDislikeRemoved.show();
findingUnlike.show();
findingDislikeBox.hide();
findingLike.hide();
}
findingDislikeCollection.each(function() {
var findingDislike = $(this).clone();
var url = findingDislike.attr("href");
findingDislike.click(function(event) {
event.preventDefault();
$.ajax({
url: url,
type: "POST",
dataType: "json",
success: function(data) {
if (data.profileState == 1) {
$('#dislike_count_btn').text('Odrzuć' + data.DislikeCount);
findingDislikeBox.hide();
findingDislikeRemoved.show();
findingUnlike.show();
//findingUnDislike.show();
//findingUnDislike.attr('disabled', false );
//findingUnDislike.text('Cofnij');
}
else {
alertBox.show();
if ($('.alert-box-msg').length==0) {
$('.alert-area').prepend('<p class="alert-area alert-box-msg">Żeby korzystać z tej funkcji musisz być zalogowany.</p>');
}
findingDislike.attr('disabled', false );
}
},
error: function() {
alert('Problem z serwerem, spróbuj ponownie za kilka minut.');
findingDislike.attr('disabled', false );
}
});
});
});
$('html').click(function (e) {
if (!$(e.target).hasClass('alert-area')) {
$('.alert-box').hide();
findingDislike.attr('disabled', false );
}
});
});
Thanks for answer
You are cloning the element with .clone which means you're not actually attaching an event listener to anything in the DOM. Cloned elements must be manually inserted into the DOM with JavaScript for them to have any effect.
This is not a correct way. Following should work:
findingDislikeCollection.click(function(event){
var findingDislike = $(this);
var url = findingDislike.attr("href");
//AJAX call
event.preventDefault();
});
More details on click event are given here:
https://api.jquery.com/click/
I've written a plugin to create long click event handler for my web application. I know it is not too advanced and that it has low functionality, but I am trying to improve it. You can see my plugin below:
$(function($) {
var holdTimer;
var timerRunning = false;
$.fn.longClick = function(handler, time) {
if (time == undefined) time = 500;
return this.on({
mouseup: function() {
clearTimeout(holdTimer);
timerRunning = false;
},
mousedown: function() {
var self = this;
timerRunning = true;
holdTimer = window.setTimeout(function() {
handler.call(self)
}, time);
}
})
};
$.fn.longClick.defaultTime = 500;
}(jQuery));
What is my problem?
I am in the situation of putting Ajax-generated content on my page, and you can easily know that .longClick() won't work anymore for those elements.
I have the following snippet:
$.ajax({
url: "/ajax/",
type: "POST",
data: {
action: "load-posts",
},
dataType: "html",
success: function(data) {
$(".profile-wrapper").append(data);
}
});
The data looks like this:
<div class="post">
<div class="comments">Comments</div>
</div>
Then I need to use the .longClick event for .comments. I found this, on Stack Overflow, and I know which my situation is, but I don't know how to modify my plugin to work like $(selector).on(event,childSelector,data,function).
How would you modify this plugin to work on dynamic content? Thank you for your patience and help.
EDIT FOR #AminJafari
The long-click event now fires, but inside the function, the .post seems to be undefined:
$(".profile-wrapper .tabs-wrapper .tab .post").longClick(function () {
var $post = $(this);
var menuTop = $post.offset().top + "px";
// ...
}
Output from the console:
Uncaught TypeError: Cannot read property 'top' of undefined
UPDATED:
$(function($) {
var holdTimer;
var timerRunning = false;
$.fn.longClick = function(handler, time) {
if (time == undefined) time = 500;
var that=$(this);
$(document).on('mouseup',that,function(){
clearTimeout(holdTimer);
timerRunning = false;
});
$(document).on('mousedown',that,function(){
var self = this;
timerRunning = true;
holdTimer = window.setTimeout(function() {
handler.call(self)
}, time);
});
};
$.fn.longClick.defaultTime = 500;
}(jQuery));
Im'm loading posts in a div #reviewspostscont, the AJAX code works and the posts are loaded when the scrollbar gets to the end but I can't reinitialise JScrollPane to show them.
I tried different codes but nothing works, this is what i have so far.
Thanks in advance, Matt
jQuery(document).ready(function($) {
$(function()
{
$('#reviewspostscont').each(
function()
{
$(this).jScrollPane(
{
horizontalDragMaxWidth : 100
}
);
var api = $(this).data('jsp');
var throttleTimeout;
$(window).bind(
'resize',
function()
{
if (!throttleTimeout) {
throttleTimeout = setTimeout(
function()
{
api.reinitialise();
throttleTimeout = null;
},
50
);
}
}
);
$(this).bind(
'jsp-scroll-x',
function(event, scrollPositionX, isAtLeft, isAtRight)
{
var count = 2;
if (isAtRight == true) {
loadArticle(count);
var api = $(this).data('jsp');
api.reinitialise();
count++;
}
}
);
}
)
});
function loadArticle(pageNumber){
$.ajax({
url: "<?php bloginfo('wpurl') ?>/wp-admin/admin-ajax.php",
type:'POST',
data: "action=infinite_scroll&page_no="+ pageNumber + '&loop_file=loop-reviews',
success: function(html){
$("#reviewspostscont").append(html); // This will be the div where our content will be loaded
}
});
return false;
}
});
You can use autoReinitialise. Here's a demo showing a similar example. And another one. And another.