I used this snippet of code (had to adapt it) to autoload (think Twitter) new posts on my page when scrolling.
Since this is resource heavy for my server when a user scrolls fast, I want it to be activated when clicking on a button, lets say <button id="load_more">Load more</button>
Can anyone help me convert mine ? I can't get it to work... (plus eventually remove the busy indicator)
Here is the code I use for autoscroll :
<?php
$maxPage = $this->Paginator->counter('%pages%');
?>
<script type="text/javascript">
var lastX = 0;
var currentX = 0;
var page = 1;
$(window).scroll(function () {
if (page < <?php echo $maxPage;?>) {
currentX = $(window).scrollTop();
if (currentX - lastX > 150 * page) {
lastX = currentX - 150;
page++;
$("#busy-indicator").fadeIn();
$.get('<?php echo $this->Html->url('/users/getmore_timeline/'.$this->Session->read('Auth.User.id')); ?>/page:' + page, function(data) {
setTimeout(function(){
$('#postList').append(data);
var bi = $("#busy-indicator");
bi.stop(true, true);
bi.fadeOut();
}, 500);
});
}
}
});
</script>
EDIT :
I tried (from memory)
<button onlick"LoadMore()">Load More</button>
<?php
$maxPage = $this->Paginator->counter('%pages%');
?>
<script type="text/javascript">
function LoadMore () {
if (page < <?php echo $maxPage;?>) {
page++;
$("#busy-indicator").fadeIn();
$.get('<?php echo $this->Html- >url('/users/getmore_timeline/'.$this->Session->read('Auth.User.id')); ?>/page:' + page, function(data) {
setTimeout(function(){
$('#postList').append(data);
var bi = $("#busy-indicator");
bi.stop(true, true);
bi.fadeOut();
}, 500);
});
}
};
</script>
i'm not sure if i missed something here, but if all you want is a button to call the function LoadMore():
HTML
<button id="load_more">Load more</button>
JS
$('#load_more').on('click', function() {
Loadmore()
})
PS: about your <button onlick"LoadMore()">Load More</button>, you have a typo (very funny one :D), forgot a equal sign, and you should avoid using inline event handlers.
Related
I am working on auto scrolling of chat application, which is like that whenever I go for a conversation to someone then the conversation page automatically scroll down and when I send a message the scroller automatically again scroll down on each send-receive message.
Using this script I achieve my goal
$(document).ready(function() {
setInterval(function() {
$('#messagepost').load('conveyrefresh.php?value=<?php echo $mid."&picture=".$profilepic; ?>').scrollTop($("#messagepost").prop('scrollHeight'))
}, 1000);
});
But problem is that when I scroll up it is not scrolling up normally, means it is not fixing on its upper position it goes to down automatically.
I want it to work normally when I scroll up or down beside auto-scrolling on each send message and on refreshing a page.
After searching its solution, I have implemented this script (in place of above)-
var scrollpos = $("#messagepost").scrollTop();
var scrollpos = parseInt(scrollpos) + 520;
var scrollHeight = $("#messagepost").prop('scrollHeight');
if(scrollpos < scrollHeight)
{
$(document).ready(function() {
setInterval(function () {
$('#messagepost').load('conveyrefresh.php?value=<?php echo $mid."&picture=".$profilepic; ?>')
}, 1000);
});
}
else
{
$(document).ready(function() {
setInterval(function () {
$('#messagepost').load('conveyrefresh.php?value=<?php echo $mid."&picture=".$profilepic; ?>').scrollTop($("#messagepost").prop('scrollHeight'))
}, 1000);});
}
But after applying it, the functionality of auto scrolling has gone.
After spending a lot of time, I got a solution and it is working for me.
<script type="text/javascript">
$("#messagepost").scrollTop($("#messagepost").prop('scrollHeight'));
$(document).ready(function()
{
function updateChat(){
$('#messagepost').load('conveyrefresh.php?value=<?php echo $mid."&picture=".$profilepic; ?>');
}
var chat = $("#messagepost").html();
setInterval(function () {
updateChat();
if(chat !== $("#messagepost").html()){
$("#messagepost").scrollTop($("#messagepost").prop("scrollHeight"));
chat = $("#messagepost").html();
}
}, 1000);});
</script>
Hi i have started making this web.
I am desperately trying to make my menus to fly-in and out on transitions. I want my menus to fly-in in a certain order starting from top to bottom.
I have updated this question from its original.
html:
<div id="flyin">
<form action="WoodEnglish.html" method="get">
<input id="Wood" type="image" src="Wood.png" alt="Submit" >
</form>
</div>
javascript:
<script type="text/javascript">
$(document).ready(function () {
var currWidth = $(window).width();
console.log(currWidth);
var startPos = -1;
var endPos = 1000;
console.log(endPos);
$('#flyin').animate({left: endPos},1000);
$('#Wood, #submit2').click(function () {
if (this.id == 'Wood') {
$('#flyin').animate({left: endPos}, 1000);
}
else if (this.id == 'submit1') {
alert('Submit 2 clicked');
}
});
});
</script>
However there is still two problems with this code
is this; var currWidth = $(window).width(); i think. I need my buttons to fly into the screen from out of screen and atm i am not allowed to do that.
atm it doesn't wait until the animation is complete before loading the next html on action form.
thx in advance for any contributions
You have referenced items in the <head>, even before they are loaded. Please wrap everything in document ready function:
$(document).ready(function () {
var currWidth = $(window).width();
console.log(currWidth);
var startPos = -100;
var endPos = (currWidth / 2) + (startPos / 2);
console.log(endPos);
$('#flyin').animate({left: endPos}, 1000);
});
Fiddle: http://jsbin.com/pafigicabo/edit?js,output
Okay i figured it out. This will make an image fly from outside the screen to inside the screen and then again fly from inside the screen to outside the screen when you click it.
$(document).ready(function () {
$('#flyin').animate({left: "1000px"},1000);
$('#Wood, #submit2').click(function () {
if (this.id == 'Wood') {
$('#flyin').animate({left: "-1000px"}, 1000);
}
else if (this.id == 'submit1') {
alert('Submit 2 clicked');
}
});
});
I need help with the following problem. There is a button on my page and the press of the button loads content in a “div” element positioned below the button via AJAX. Everything works fine but one thing. The page scrolls a bit with each press of the button but I want it to keep its position.
Here is my HTML code:
<input type="button" name="calculate" value="Calculate"
onclick="invoke(this.form, this.name, '#result')"/>
And here is my JavaScript code (I am using jQuery):
function invoke(form, event, container) {
$('input[type="button"]').attr('disabled', 'disabled');
$(container).html('<br/><div class="img"><img src="/Test/img/ajax-loader.gif"/><div>');
$(container).load(form.action, event + '&' + $(form).serialize());
}
I searched through other posts but didn’t find any working solution. Any suggestions would be appreciated!
I found out where the problem came from. Since the content loaded in the “div” element changed its height 2 times with each press of the button, the height of the page body changed as well. This was the cause of the scrolling. I fixed the height of the “div” element in the css file:
div#result {height: 200px;}
This solved the problem.
Good, for the answer and also good if you give your code in jsfiddle. Still no issue, recently I have done the same thing.
By default it same position if you click on button, but if you have anchor tag, then it will automatically goes on top.
There is so many things to stay or scroll on desired position.
window.scrollTo(0, 0);
function buttonclick(isfirsttimeload)
{
if (typeof isfirsttimeload!= "undefined")
window.scrollTo(0, 0);
else
location.hash = '#asearchresult'; //this is hidden anchortag's id, which scrolldown on click.
}
http://www.w3schools.com/jsref/prop_loc_hash.asp
Using window.location.hash in jQuery
You have to call this function on page load.
limit – The number of records to display per request.
offset – The starting pointer of the data.
busy – Check if current request is going on or not.
The main trick for this scroll down pagination is binding the window scroll event and checking with the data container height
$(document).ready(function() {
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
displayRecords(limit, offset);
}
});
})
<script type="text/javascript">
var limit = 10
var offset = 0;
function displayRecords(lim, off) {
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$('#loader_image').hide();
$("#results").append(html);
if (html == "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#loader_message").html('<button class="btn btn-default" type="button">Load more data</button>').show();
}
}
});
}
$(document).ready(function() {
// start to load the first set of data
displayRecords(limit, offset);
$('#loader_message').click(function() {
// if it has no more records no need to fire ajax request
var d = $('#loader_message').find("button").attr("data-atr");
if (d != "nodata") {
offset = limit + offset;
displayRecords(limit, offset);
}
});
});
</script>
Implementing with php ie getrecords.php
<?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT countries_name FROM countries WHERE 1 ORDER BY countries_name ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<h3>' . $res['countries_name'] . '</h3>';
}
}
?>
Here is the code sample and I its working all perfectly just the case is it loads further ajax request when the scroll bar hits the bottom, I want to make it load when it may reach upto 90% and beyond that form top.
$count = sql::read("SELECT COUNT(table_column_name) as count FROM table_name WHERE Info ='".$info."'");
$actual_row_count = $count[0]->count;
<script type="text/javascript">
$(document).ready(function(e) {
var page = 1;
var flag = 0;
$(window).scroll(function () {
$('#more').hide();
$('#no-more').hide();
if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
$('#more').css("top","400");
if(flag == 0)
{
$('#more').show();
}
}
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$('#more').hide();
$('#no-more').hide();
page++;
var data = {
page_num: page,
info : '<?php echo $info; ?>'
};
var actual_count = "<?php echo $actual_row_count; ?>";
if((page-1)* 12 > actual_count){
$('#no-more').css("top","400");
$('#no-more').show();
flag = 1 ;
}
else{
$.ajax({
type: "POST",
url: "data.php",
data:data,
success: function(res) {
$("#result").append(res);
console.log(res);
}
});
}
}
});
});
</script>
What you need is to calculate if bottom of current viewport beyond 9/10 of total document height or not. Consider following expression, it might help:
($(window).scrollTop() + $(window).height()) / $(document).height() > 0.9
However, you main problem caused by the fact that scroll event fires multiple time per second. Therefore it make all possible calls before single ajax request has been resolved. You need to unattach event handler before making first call and reattach it after ajax succeed.
For example:
var win = $(window);
function onScroll() {
...
if (90% document scrolled) {
win.off('scroll', onScroll);
$.ajax({
...
success: function(res) {
$("#result").append(res);
win.on('scroll', onScroll);
}
});
}
}
win.on('scroll', onScroll);
I am trying to run this function set_downloads($file[0]); when the download button is clicked, i can't just add it in the code, as it will run. I can put it on a different page and do some sort of onclick event to load it, but i don't know how to do this.
<script type="text/javascript">
var x = 0;
var r = 0;
function countdown() {
if (x > 1) {
x--;
document.getElementById("button").innerHTML = x;
r = setTimeout("countdown()",0);
}
else {
clearTimeout(r);
document.getElementById("button").innerHTML = "Click to download (<?php echo $filesize;?>) ";
document.getElementById("button").disabled = "";
document.getElementById("button").onclick = function() {
document.getElementById("button").disabled = "disabled";
document.getElementById("button").innerHTML = "Your download is starting..";
};
}
}
setTimeout("countdown()",1000);
</script>
</head>
<body>
<label>
<font size="5"></font>
</label>
<a href="http://IP/uploads/<?php echo $fullfile; ?>" >
<button class="btn large orange" id="button" disabled="disabled">Click to download (<?php echo $filesize;?>) </button>
</a>
$(document).ready(function(){
var x = 0;
var r = 0;
function countdown() {
if (x > 1) {
x--;
document.getElementById("button").innerHTML = x;
r = setTimeout("countdown()",0);
}
else {
clearTimeout(r);
document.getElementById("button").innerHTML = "Click to download (<?php echo $filesize;?>) ";
document.getElementById("button").disabled = "";
document.getElementById("button").onclick = function() {
document.getElementById("button").disabled = "disabled";
document.getElementById("button").innerHTML = "Your download is starting..";
};
}
}
setTimeout("countdown()",1000);
$('.btn').click(function(){
set_downloads($file[0]);
});
});
This event handler is what you want to use to handle events. It uses a callback, which calls that function argument after the button is clicked.
The other thing is, I'm not sure about your $file[0] variable, or where your set_downloads function is defined. where do you set these?
Correct me if I am wrong but could you not just use a $(document).ready(handler) to ensure the DOM is loaded if needed then just use a onclick as you suggested:
.click( [eventData], handler(eventObject) )
eventDataA map of data that will be passed to the event handler.
handler(eventObject)A function to execute each time the event is triggered.
EDIT:
$('#button').click(function(){
set_downloads($file[0]);
});
Not sure if you would really need this inside a ready() but if so, you would just enclose the function for click() inside here:
$(document).ready( {
// Function for button goes here
});
EDIT#2
$(document).ready({
$('.btn').click(
{
$.ajax({ url: 'script.php?argument=value&foo=bar' });
)};
));
You could place your php script inside a seperate file and call it using ajax and the url: then set any arguments if needed. I wouldnt copy and paste what I put considering I am mobile and its difficult to see brackets :/
You could also take a look here, A slightly different example still using Ajax and Jquery but may work slightly nicer for your desired application:
Use Ajax to call PHP function for HTML button Onclick