I am looking for a solution to display many items (10's of thousands) in a list view in Yii. I would like to be able to display them in a continually scrollable list. Here is the catch, when the user scrolls past the end of the list I want the new data to replace the data he just scrolled passed. Kind of like google music if you have a really long play list.
I looked at Yiinfinite-scroller but it appends to the end of the list making a very long list which is killing my memory usage.
Thanks
Its actuality really easy to implement infinite scroll in just a few lines of js and with the help of jQuery. Measure the height of the content div and as the page scrolls subtract the scroll difference from the divs height then when it hit the min amount do the query for more content and reset the height counter and repeat:
<script type="text/javascript">
var contentHeight = 4000,;
var pageHeight = document.documentElement.clientHeight;
var scrollPosition;
var n = 1;
function scroll(){
if(navigator.appName == "Microsoft Internet Explorer")
scrollPosition = document.documentElement.scrollTop;
else
scrollPosition = window.pageYOffset;
if((contentHeight - pageHeight - scrollPosition) < 500){
$.ajax({ url: "./yourAPI/?next="+n, cache: false,
success: function(data){
//append result
$('#infscroll').append('<div>'+data.result+'</div>');
}, dataType: "json"});
n += 1;
contentHeight += 4000;
}
}
$(document).scroll(function(){
setInterval('scroll();', 250);
});
</script>
<div id="infscroll"></div>
Related
my apologies if its an incomplete or irrelevant question but I am having a big problem in my code. By using ajax I call a list of hotel rooms using an API. Now I call separate asynchronous ajax requests using JQuery to get cancellation policy of these rooms. The ajax requests are going to single PHP script on the server. If cancellation policy is present then show the book button for the room and if cancellation policy is not present then hide the room.
Now the issue is that suppose there are 5 rooms and one room returns cancellation policy 1st I show its book button which is an anchor tag with href to checkout page. But if I click on this anchor tag the page takes 15-20 seconds more before it goes to the href location.
Kindly let me know what can I do to reduce this time or what can I do to check where my page is spending these 15-20 seconds.
If needed I can provide links to test this module on my staging link.
Thanks.
var xhrRequests = [];
function filterByCancellation(){
$( ".hotel_package_row:visible" ).each(function( index ) {
var cancellation_obj = $(this).find( ".cancellationText" );
var pack_price = 0;
var hotel_price = 0;
if ($(cancellation_obj).text()=="") {
var hotelid = $(cancellation_obj).prev("a").data( "hotelid"),
packid = $(cancellation_obj).prev("a").data( "packid"),
cancel = $(cancellation_obj);
if(!$('#anc-'+packid).is(':visible') && $('#inp-'+packid).val()=="0"){
$('#inp-'+packid).val("1");
cancel.html('').slideToggle(function(){
var data = { hotelid: hotelid, packid: packid };
pack_price = parseInt($('#packprice_'+packid).val());
var xhr = $.ajax({
type: "POST",
url: "location_penny.php?section=cancellationData",
data: data,
success: function(result) {
//cancel.html(result);
if(result.indexOf('<div style="display:none;">') > -1){
$(cancellation_obj).parents('.hotel_package_row').html('');
}else{
hotel_price = parseInt($('#'+hotelid).find('.currency-sign-before').html());
if($("#price_update_"+hotelid).val()=='0'){
//alert("hotel price "+hotel_price+" updating for the first time with package "+pack_price);
$('#'+hotelid).find('.currency-sign-before').html(pack_price);
$("#price_update_"+hotelid).val("1");
}
if(pack_price<=hotel_price){
//alert("hotel price "+hotel_price+" is greater than current package price "+pack_price);
$('#'+hotelid).find('.currency-sign-before').html(pack_price);
}
$('#img-'+packid).hide();
$('#anc-'+packid).show();
}
},
async:true
});
xhrRequests.push(xhr);
});
}
}
});
}
function cancelXhrRequests(){
for (var i = 0; i < xhrRequests.length; i++) {
//xhrRequests[i].abort();
}
}
I added this shout box from http://www.saaraan.com/2013/04/creating-shout-box-facebook-style
a live demo of it can be seen here http://www.saaraan.com/2013/04/creating-shout-box-facebook-style
I have everything working properly except the slider itself. Every time I try to scroll up, it automatically scrolls back down. It wont stay in the up position. I think the problem is here.
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('.message_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
//reset value of message box
$('#shout_message').val('');
More specifically here
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
and here
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
I have changed the 0 to 1 and other numbers and it fixes the scroll to work right but it doesn't show the latest shout, it will show shout 25 which is the last shout to be seen before deletion. Im not sure if this makes any sense but any help would be great.
The first link from top shows the whole code, the second link shows the example
Try this code, I didn't tested it. I hope it will work.
window.setInterval(function() {
$.post( 'shout.php', load_data, function( data ) {
var old_data = $(".message_box").html();
if ( old_data != data ) {
$(".message_box").html( data );
// get scrollHeight
var scrollHeight = $(".message_box").get(0).scrollHeight,
// get current scroll position
scrollTop = $(".message_box").scrollTop(),
// calculate current scroll percentage
percentage = Math.round( ( 100 / scrollHeight ) * scrollTop );;
// make sure user is not scrolled to top
if ( percentage > 80 ) {
$(".message_box").scrollTop( scrollTop );
}
}
});
}, 1000);
My question has part solutions on this site but not a complete answer.
On my wordpress homepage I display a counter of the number of questions answered within our webapp. This is displayed using jQuery and AJAX to retrieve the question count from a php file and works fine with this code.
jQuery(document).ready(function() {
function load() {
jQuery.get('/question_count.php', function(data) {jQuery('#p1').html( data ); });
}
load();
setInterval(load,10000);
});
Is there a way to display counting up to the new number retrieved rather than just immediately displaying it?
Something like this?
function countTo(n) {
var p = $("#p1"),
c = parseInt(p.html(), 10) || 0,
dir = (c > n ? -1 : 1); // count up or down?
if (c != n) {
p.html((c + dir) + "");
setTimeout(function() {
countTo(n);
}, 500);
}
}
Call it in your success handler
jQuery.get('/question_count.php', function(data) {
var n = parseInt(data, 10);
countTo(n);
});
Example
You will need to do a setInterval event so that the count up is visable to human eyes.
This may be a problem if you eventually reach enough questions where the count takes a long time to reach the end.
Code will look like this:
function load(){
jQuery.get('/question_count.php', function(data){
var curr = 0;
var max = parseInt(data);
var interval = setInterval(function(){
if(curr==max){
clearInterval(interval);
}
jQuery('#p1').html( curr );
curr+=1; //<-- if the number of questions gets very large, increase this number
},
10 //<-- modify this to change how fast it updates
});
}
}
This question already has an answer here:
How to paginate query results for Infinite Scroll?
(1 answer)
Closed 8 years ago.
Infinite scroll should stop after 10 rows of records. If there are more records, ajax pagination should be displayed. For example, consider this infinite scrolling example.
So after 20 records I want to display pagination and same should be done on next page. Please let me know if you have any of this ideas or solution.
Here is my code on which I am working:
//On doMouseWheel = 1 I have taken the currentdealoffset value and check it with the total no of deals present
//If count is less, then simply calculating the window position displaying the allotted records say 10
//On next scroll just doing the same process and fetching records using ajax until end of the deals
//Now the problem is I am not able to code a logic where after say 10 records show a pagination and
//When click on next page the same process should be managed by fetching the offset count of scrol and offset of pagination bar
doMouseWheel = 1 ;
$(window).scroll(function() {
if($('#facebox_overlay').is(':visible')==false){
$('#endofdeals').show();
$('#endofdeals').html("<center><img src='"+SITEIMG +"ajax-loader_1.gif' ><center>");
//console.log("Window Scroll ----");
var currentdealoffset = 0; //alert(currentdealoffset);
var currentdealoffset = parseInt(document.getElementById("countval").value); //alert(currentdealoffset);
var displaymode = parseInt($('#displaymode').val());
var totalcountdeal = parseInt($('#totaldeals').val()); //alert(totalcountdeal);
if(currentdealoffset<totalcountdeal){
if (!doMouseWheel) {
return ;
} ;
var distanceTop = $('#last').offset().top - $(window).height();
if ($(window).scrollTop() > distanceTop){
//console.log("Window distanceTop to scrollTop Start");
doMouseWheel = 0 ;
$('div#loadMoreComments').show(5000);
//console.log("Another window to the end !!!! "+$(".postedComment:last").attr('id'));
$.ajax({
type : 'POST',
dataType : "html",
data: {
typeday : $('#remdumtype').val(),
catid : $('#catid').val(),
},
url: "<?php echo https_url($this->config->item('base_url'))?>popup/dealsearch",
success: function(html) {
doMouseWheel = 1;
if(html){
if(displaymode==12)
$('#listTable tr:last').after(html);
else
$("#postedComments").append(html);
//console.log("Append html--------- " +$(".postedComment:first").attr('id'));
//console.log("Append html--------- " +$(".postedComment:last").attr('id'));
$("#last").remove();
$("#postedComments").append( "<p id='last'></p>" );
$('div#loadMoreComments').hide();
$('#endofdeals').hide();
}
}
});
}
}
else
{
if($('#endofdeals')!='')
{
$('#endofdeals').hide();
if(currentdealoffset < displaymode)
{
$('#endofdeals').hide();
}else if(currentdealoffset > displaymode)
{
$('#endofdeals').show();
$('#endofdeals').html("<center><h2 style='color:#4C335B'>End of deals !!!!!!!</h2></center>");
}
}
}
}
});
According to me, You want page numbers but the pages should load slowly as you scroll.
If this you want then, you should not use Infinite scroll technique but LazyScroll will help you and if you want 20 records then make your query for 20 records also create pagination below
Here, you can have the Plug-in and Demo.
I have just started out with .php/Java can someone show me how to get my bootstrap progress bar to increment in accordance with a users set time.
Progress Bar:
Code:
<div class="progress progress-striped active">
<div id="progressbar" class="bar" style="width: 0%;"></div>
User Input Example:
Code:
Set Seconds:
<input type="text" id="speed" value="10" />
<input type="submit" value="Start" onclick="doProgress();" />
Java Script {needed}:
Code:
<script type="text/javascript">
function doProgress()
{
Idk :( Please help.
};
</script>
(style="width: 0%;") Is the progress bars value 100% being maximum.
I want the value to increase in accordance to the users set value in seconds using this element I provided:
<input type="text" id="speed" value="10" />
example: the user enters 30 I want it to take 30 seconds for the progress bar to reach 100%
Something like this (untested):
function doIncrement(increment) {
w = parseInt(document.getElementById('progressBar').style.width);
document.getElementById('progressBar').style.width= (w + increment) +'%';
}
var w
var speed = document.getElementById('speed').value;
var increment = (speed/100);
for(var x = 0; x<speed; x++)
{
setTimeout(doIncrement(increment),1000);
}
The setTimeout approach (as per other answers) is the most common approach for animating time-based progress.
But I've had a problem with setTimeout if the speed is fast or when I want to reset the bar from 100% to 0%, as the default Bootstrap css transitions lead to undesirable animation effects (i.e takes 0.6 seconds to return to 0%). So I suggest tweaking the transition styling to match the desired animation effect e.g
pb = $('[role="progressbar"]')
// immediate reset to 0 without animation
pb.css('transition', 'none');
pb.css('width', '0%');
// now animate to 100% with setTimeout and smoothing transitions
pb.css('transition', 'width 0.3s ease 0s');
var counter = 0;
var update_progress = function() {
setTimeout(function() {
pb.attr('aria-valuenow', counter);
pb.css('width', counter + '%');
pb.text(counter + '%');
if(counter<100) {
counter++;
update_progress();
}
}, 5 * 1000 / 100); // 5 seconds for 100 steps
};
update_progress();
But if you're in the jQuery camp, then jQuery.animate is I think a neater approach as you can forget having to mess with css transition styling and counting steps etc e.g.
pb = $('[role="progressbar"]')
pb.css('transition', 'none'); // if not already done in your css
pb.animate({
width: "100%"
}, {
duration: 5 * 1000, // 5 seconds
easing: 'linear',
step: function( now, fx ) {
var current_percent = Math.round(now);
pb.attr('aria-valuenow', current_percent);
pb.text(current_percent+ '%');
},
complete: function() {
// do something when the animation is complete if you want
}
});
I've put a demo and more discussion on GitHub here.
I'm just learning bootstrap myself and came up with this for advancing it. As mentioned in other answers, the width CSS property appears to be what triggers the animation, but I initially didn't notice it and set the related aria attribute. You probably want to ensure setting the width results in other related attributes getting properly updated if a11y is important to you, setting them as necessary if not.
$( function() {
var bar = $('div.progress-bar');
var val = null;
i1 = setInterval(function() {
val = parseInt(bar.attr('aria-valuenow'));
val += 10;
console.log(val);
if( val < 101) {
bar.attr('aria-valuenow', val);
bar.css('width', val + '%');
} else {
clearInterval(i1);
}
}, 1000);
});
Try this:
//Find the div you want to update
var divArray = document.getElementById('progressbar');
//Set the width style
divArray.style.width = '100%';