Why wont this shout box slider work properly? - php

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);

Related

Page spending a lot of time before processing href of anchor tag after anchor is clicked

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();
}
}

how js elements must work for new htm's loaded with ajax

i have a page for view photos and users can submit comment on it
i write a js file name(ajax.js) to load new comment with ajax every 30 sec on that pages
i write another js file (name feed.js) for when user click on delete icon near every comment comment go hide and delete
codes feed.js:
$('a[cm-del]').click(function () {
var cmid = $(this).attr('cm-del');
var typeid = $(this).attr('data-type');
$('li[last-id=' + cmid + ']').effect('pulsate');
$('li[last-id=' + cmid + ']').hide(300);
$.post('/post/comment.php', {
cmdelete: cmid,
type: typeid
}, function () {});
});
codes ajax.js:
function getmorecmphoto() {
$('li[data-hiv]').hide();
var lastid = $('li[last-id]:last').attr('last-id');
if (lastid === '') {
var lastid = 0;
}
var oldcm = $('div[comments-id]').html();
var photoid = $('div[comments-id]').attr('comments-id');
$.post('/post/photo.php', {
lastid: lastid,
photoid: photoid
}, function (getlastcmphoto) {
$('div[comments-id]').html(oldcm + getlastcmphoto);
});
}
setInterval(getmorecmphoto, 25000);
when for first time user open this page its load last 10 comment
and everythings work fine and nice
but after 25-30 sec when new comment load with ajax
my feed.js not work for new comments?
what i must to do about this?
i put feed.js load every time when new comments load buts its bad cuz in 10 minute user have about 20 feed.js loaded !
can i do something else?
thank you
You need event delegation, bind the event to the nearest static (not dynamically loaded) container and delegate the actions.
Change this:
$('a[cm-del]').click(function(){
To this:
$(document).on('click','a[cm-del]',function(){
I don't know how your markup looks like so I'm using the document as a fallback here.
Note: If you're using jQuery <1.7 use live() instead of on()
$('a[cm-del]').live( 'click', function(){
I think .live should work.
$('a[cm-del]').live("click",function(){
var cmid = $(this).attr('cm-del');
var typeid = $(this).attr('data-type');
$('li[last-id='+cmid+']').effect('pulsate');
$('li[last-id='+cmid+']').hide(300);
$.post('/post/comment.php',{cmdelete:cmid,type:typeid},function(){
});
});
If not work then do like this ..
first change the feed.js like
function SetEvent(){
$('a[cm-del]').unbind("click").click(function(){
var cmid = $(this).attr('cm-del');
var typeid = $(this).attr('data-type');
$('li[last-id='+cmid+']').effect('pulsate');
$('li[last-id='+cmid+']').hide(300);
$.post('/post/comment.php',{cmdelete:cmid,type:typeid},function(){
});
});
}
Now change ajax.js like
function getmorecmphoto(){
$('li[data-hiv]').hide();
var lastid = $('li[last-id]:last').attr('last-id');
if(lastid === ''){
var lastid = 0;
}
var oldcm = $('div[comments-id]').html();
var photoid = $('div[comments-id]').attr('comments-id');
$.post('/post/photo.php',{lastid:lastid,photoid:photoid},function(getlastcmphoto){
$('div[comments-id]').html(oldcm + getlastcmphoto);
SetEvent();
});
}
setInterval( getmorecmphoto, 25000 );
I think it will work. Thanks
I think you can fix that by changing first line of your feed.js code to this: $('a[cm-del]').live('click', function(){

Retrieving mysql data using ajax and then manipulating it

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
});
}
}

How to get the index of updated point in graph using Highcharts and how to reload the data till that index

Hello I am getting my data from csv file and I am using 'this.update(0)' on my chart to update any point through a mouse click therefore making that point equal to 0 on y axis but what I want is that when I click on a point it first gets me the index of that point and then reload the data again from same csv file but this time the data values should not go beyond the index. e.g if I clicked on a point at x=10 then I should be able to reload the data again from file till x=9 and store the newly loaded data to an array.
Here is a part my code where data has to be reloaded. It reloads the entire data which is not need, that's probably I am not getting the right index or if there is someother problem kindly help. Thank you.
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
var x= this.update(0);
$.get('testFile.csv', function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if(itemNo<x){
series.data.push(parseFloat(item)); } });
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
});
To get index use: this.series.processedXData.indexOf(this.x)
Now, remove creating new chart, but instead update each of points with values, something like this:
var actSeries = this.series; //needed for scope range
...
...
...
$.each(items, function(itemNo, item) {
if(itemNo<x){
actSeries.data[itemNo].update(parseFloat(item), false);
});
});
actSeries.chart.redraw();

Infinite Scrolling in Yii

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>

Categories