Scroll to top after Ajax content load - php

Is there anyway that I can make it so the page will automatically scroll to the top after the content has loaded (via Ajax)?
This is the code I have for displaying the content:
$(document).ready(function () {
var my_layout = $('#container').layout();
$("a.item_link").click(function () {
$("#loader").fadeIn();
feed_url = $(this).attr("href");
$.ajax({
type: "POST",
data: "URL=" + feed_url,
url: "view.php",
success: function (msg) {
$("#view-area").html(msg);
$("#loader").fadeOut();
}
});
return false;
});
});
So after the 'view-area' has loaded its content can I make the page auto scroll to the top?

Just use the scroll function
scrollTo(0);
If you want the jquery, then here is a good example with smoothing :)
From the link:
$('html, body').animate({ scrollTop: 0 }, 0);
//nice and slow :)
$('html, body').animate({ scrollTop: 0 }, 'slow');
To put it in your code
...
success: function (msg) {
$("#view-area").html(msg);
$("#loader").fadeOut();
//Put code here like so
$('html, body').animate({ scrollTop: 0 }, 0);
}

You can do $(window).scrollTop(0);

All ajax requests have a callback argument so use scrollTop(0).
Check the jQuery documentation on how to use ajax callbacks.

If you have no callback, try to bind an event listener:
document.addEventListener(
"load",
function(event) {
event.composedPath().forEach(function(dom) {
if (dom.classList && dom.classList.value === "classOfLoadedContent") {
$(".div-to-be-scrolled").scrollTop($(".content").innerHeight());
}
});
},
true
);

Related

jQuery Live Search keyup show loading

I am trying to display a loading animation and hide the search input box before the ajax request has been sent, the ".se-pre-con" element is the loader.
As you can see below I am tring to show this in the beforeSend of the ajax request. However, when the user is typing in the search box then stops for the delay specified (1000ms) the input box still displays throughout the ajax request but it is unresponsive.
Then the results are returned, and the loading animation does the fadeOut so it the show() must be triggering but the page remains unchanged until the results are returned. I want to prevent the unresponsive page effect and show a loading animation during the request. Any help is much appreciated.
$(document).ready(function() {
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#search_field').keyup(function() {
var target = $(this);
delay(function() {
getSearchResults(target.val());
}, 1000);
});
function getSearchResults(str) {
$.ajax({
beforeSend: function(){
$(".se-pre-con").show();
$("#search_field").hide();
},
url: "http://example.com/Search_Results.php",
dataType:"html",
data: {"search_term": str},
method: "post",
async: false,
success: function(data){
if(data !== null) {
$("#search_default").hide();
$("#search_results_wrapper").html(data);
}
$(".se-pre-con").fadeOut("slow");
$("#search_field").show();
$("#search_field").focus();
},
error: function(){
$(".se-pre-con").fadeOut("slow");
$("#search_field").show();
$("#search_field").focus();
}
});
}
});
I found the solution.
Solution
It started working when I removed the option:
async: false

Ajax sometimes freezes

This code is supposed to request new chat messages and append them to the content on my website. The problem, though, is that it sometimes freezes and stops requesting new messages.
(function worker() {
$.ajax({
url: '/client_message.php?get_message=yes&chat_id=<?php echo $chat_id; ?>&user_id=<?php echo $uid; ?>',
success: function(data) {
content = data;
if(content != "" && content != prev) {
$("#chat_wrapper").append(content);
prev = content;
$("html, body").animate({ scrollTop: $(document).height() }, "slow");
titleStuff();
}
},
complete: function() {
setTimeout(worker, 700);
}
});
})();
Please let me know if you need more information to figure out what could be wrong.
Adding this code did the trick:
$.ajaxSetup({ cache: false });
Seems like the problem was a result of the jQuery cache.

auto refresh ajax div running on php page

Please see my code below. I want to auto refresh a div on a php page. I tried to refresh through javascript and html header, but it is slowly slowing down my computer.
page2.php
<?php
if($_GET['type']!='ajax'){
include 'header.php';
echo "<div id='main-content'>";
}
?>
Itm 1</br>
Itm 2
<img class="ajax-loader" src="ajax-loader.gif" alt="loading..." />
<?php
if($_GET['type']!='ajax'){
echo "</div>";
include 'footer.php';
}?>
app.js
$.cergis = $.cergis || {};
$.cergis.loadContent = function () {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
if (pageUrl != window.location) {
window.history.pushState({ path: pageUrl }, '', pageUrl);
}
}
$.cergis.backForwardButtons = function () {
$(window).on('popstate', function () {
$.ajax({
url: location.pathname + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
}
});
});
}
$("a").on('click', function (e) {
pageUrl = $(this).attr('href');
$.cergis.loadContent();
e.preventDefault();
});
$.cergis.backForwardButtons();
i have tried different variation but no luck. please help me.
thanks.
app.js changed...
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
}
});
}
setInterval(function(){myTimer()}, 1000);
Try setTimeout:
function myTimer() {
$('.ajax-loader').show();
$.ajax({
url: pageUrl + '?type=ajax',
success: function (data) {
$('#main-content').html(data);
// hide ajax loader
$('.ajax-loader').hide();
setTimeout(myTimer,1000);//so that the request ends setTimeout calls a new request.
},
error: function () {
setTimeout(myTimer,1000);//If there is an error in the request the "autoupdate" can continue.
}
});
}
myTimer();//fire
this way setTimeout() waiting to finish the request to invoke a new request.
setInterval() does not wait, which makes simuntaneos generate multiple events, which causes the slowness.
You can use setTimeout($.cergis.loadContent, 1000); to refresh once or setInterval($.cergis.loadContent, 1000); to refresh each seconds (1000 milliseconds = 1second).
See http://www.w3schools.com/js/js_timing.asp

php autoscroll issues with .js

Is there any SIMPLE way to create an autoscroll within a php/html chatbox?
I tried a few things, but they all interfered with other .js elements on the page and all end up not working.
to view live code of the chatbox click here!
heres what i have at the moment
// jQuery Document
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2500); //Reload file every 2.5 seconds
//If user wants to end session
$("#exit").click(function(){
var exit = confirm("Are you sure you want to end the session?");
if(exit==true){window.location = 'index.php?logout=true';}
});
});
I suspect the weight you get your scroll height doesn't work. I have tried to type it in the command line of FF and didn't get an int nor an object.
Don't try to get the scroll height. Scroll further down... and more than that.
$("#chatbox").animate({ scrollTop: 99999 }, 'normal');
I have only tried with FF, but should work across most browsers.
Then, your success function is dead simple :
success: function(html){ $("#chatbox").animate({ scrollTop: 99999 }, 'normal');
$("#chatbox").html(html);
$("#chatbox").animate({ scrollTop: 99999 }, 'normal');
}
$(".msgln").last().offset().top

How to request page content by clicking a div with jQuery mobile?

I am trying to fetch data form a callback page (php) and load it into a html div with jQuery mobile. This should happen if a user clicks on another div.
What I actually got is
$.('#home-button').bind('vclick', function( e ) {
$.get('homeCallback.php',function(data){
$('#displayContent').append(data).trigger('create');
},'html');
});
Where #home-button is the div that should trigger the event and #displayContent the div where the content should be put in.
The request should be able to pass some parameters, too. Like homeCallback.php?param=1 but it could also use the post method.
The callback does not have to be html only, it could also be possible that the callback php script provides JSON data or anything.
I am not a JS crack so I have problems solving this issue. Thanks for your help!
Edit:
So I found a solution on my own:
$(document).ready(function() {
$.ajaxSetup ({
cache: false
});
var ajaxLoader = '<img src="images/ajax-loader.gif" alt="loading.." />';
var loadUrl = "homeCallback.php";
$('#home-button1').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option1',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
$('#home-button2').click(function(){
$('#displayContent').toggle('fast', function() {
$(this).html(ajaxLoader);
$(this).toggle('fast', function() {
$.get(loadUrl + '?option2',function(data){
$('#displayContent').html(data);
},'html');
});
});
});
});
And this is what homeCallback.php simply does..
<?php
if( isset($_GET["option1"] ))
echo "option1";
if( isset($_GET["option2"] ))
echo "option2";
So far.
$.('#home-button').bind('click', function() {
$.ajax({
url: "homeCallback.php",
type: "POST",
data: ({param: 1, param2: 2}),
success: function(html){
$("#displayContent").html(html);
}
});
});

Categories