i have written a javascript inside the php file, but while calling it from my main page like this
<script type="text/javascript" src="<?php echo base_url() . 'js/inf-scroll/javascript_showuserinst.php' ?>"> </script>
Problem: if i see in the javascript_showuserinst.php file a line as $.post('/instruction/show_user_inst/<?php echo $userid; ?>', {
here <?php echo $userid; ?> is giving me problem. Is that line syntax is correct?
I see the view source its showing <b>Notice</b>: Undefined variable: userid in <b>D:\xampp\htdocs\js\inf-scroll\javascript_showuserinst.php</b> on line <b>46</b><br />
But if i copy & paste the same js content in the main page without calling it from external file, it works perfectly.
javascript_showuserinst.php
Header("content-type: application/javascript");
?>
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Data To Display!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
.............
.............
JavaScript files are expected to contain JavaScript.
Your JavaScript file contains a fragment of HTML.
Don't include HTML <script> tags in a JavaScript file.
<?php
echo "<script type='text/javascript' src='".base_url()."js/inf-scroll/javascript_showuserinst.php"."'></script>"
?>
This must be in your PHP Script File
<script type="text/javascript" src="<?php echo base_url() . 'js/inf-scroll/javascript_showuserinst.php' ?>"> </script>
Now javascript_showuserinst.php can be like below
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Data To Display!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = 'No more data to show';
else $initmessage = 'Click for more';
// Append custom messages and extra UI
$this.append('<div class="content"></div><div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('/instruction/show_user_inst/<?php echo $userid; ?>', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('.content').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('Loading...');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
Try it out
Related
I have a php page with a nav and a content div. When I choose an option in the nav, the content is modified by loading another php file inside it. For this I use ajax with load function. My problem is that if I right click and select open in a new tab or a new window, evidently, only the content is open in the tab.
I know that I can have the whole page (container + content) in each php file and load only the content div, but I think there is no much sense in this.
Is there any way to get the container along the content in the new tab?
I already had a similar situation, the tabs have pages, and the menu was in the top page. you can apply this solution:
This logic will work with iframe, if you are using divs, you can adjust for this:
main page with the nav menu, here you need apply some logic like this:
<script>
//Object to get values of URL (GET)
var request = {
get get() {
var vars = {};
if (window.location.search.length !== 0)
window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
key = decodeURIComponent(key);
if (typeof vars[key] === "undefined") {
vars[key] = decodeURIComponent(value);
}
else {
vars[key] = [].concat(vars[key], decodeURIComponent(value));
}
});
return vars;
},
getParam: function (param) {
var vars = request.get;
if (vars[param] != undefined) {
return vars[param];
} else {
return null;
}
}, getParams: function () {
return request.get;
}
};
//variable that defines if the client are in mainWindow
window.mainWindowFrame = true;
var tabName = request.getParam("tab");
console.log("tabName",tabName);
//call some function to reload the content of iframe or div to requested tab.
//if(tabName != null || tabName != ""){
//tabs.load(tabName) ....
//}
</script>
In the pages of content you need aplly this piece of code to reload the page if the menu are not present:
<script>
//name of this tab
var tabName = "someTab";
//check if the menu are present here
if(window.top.mainWindowFrame == undefined){
window.location.href = "mainpage.html?tab="+tabName;
}
</script>
I'm affronted to another jQuery problem. Well I'm beginning by my code to understand my issue here:
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
$(window).scroll(function(e){
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
$(window).scrollTop(60);
});
});
});
}
});
</script>
My problem is based on infinite scroll but instead of "append" I used html() function to replace content in a div called annonceis.
The idea is that when I'm scrolling to bottom of the page I get content of new page called index.php?page=1 2 3. And replace old content in de div annonceis with the new content that I get with jQuery, but when I scroll to the bottom I Get content of next next page ex when the current page is index.php?page=2 normally when I scroll to bottom I must get content of index.php?page=3 but here I get content of index.php?page=3 and instantly index.php?page=4 so the page display index.php?page=4.
The main idea is scrolling to bottom and get the content of the next page instead of pagination, but it must take care about history.pushState for SEO purpose and Google suggestions see http://scrollsample.appspot.com/items and that https://googlewebmastercentral.blogspot.com/2014/02/infinite-scroll-search-friendly.html.
Thank you very much in advance.
So, what you're after really is pagination combined with infinite scroll. What the provided example is doing is using .pushState() to track the users scroll using page Waypoints. Notice, once page X reaches the center point in the page, the .pushState() is triggered.
Secondly, if you look at the example's source code for any of the pages, you'll see it will only render the selected page, then using listeners on the .scroll it will append or prepend content as needed.
So, at it's core, this is really just simple pagination. The infinite scroll feel is simply added on top for user experience. Basic overview to do this would look something like this:
Model or Controller
Your PHP file or whatnot, that runs the actual queries - class based for ease of use. The class will contain one function to grab a set of posts based on a request page. JavaScript will handle everything else.
<?php
Class InfiniteScroller {
// Set some Public Vars
public $posts_per_page = 5;
public $page;
/**
* __construct function to grap our AJAX _POST data
*/
public function __construct() {
$this->page = ( isset($_POST['page']) ? $_POST['page'] : 1 );
}
/**
* Call this function with your AJAX, providing what page you want
*/
public function getPosts() {
// Calculate our offset
$offset = ($this->posts_per_page * $this->page) - $this->posts_per_page;
// Set up our Database call
$SQL = "SELECT * FROM my_post_table ORDER BY post_date ASC LIMIT " . $offset . ", " . $this->posts_per_page;
// Run Your query, format and return data
// echo $my_formatted_query_return;
}
}
?>
AJAX Call
The next thing you'll want to take care of is your frontend and JavaScript, so your AJAX call can sit in a function that simply calls the above method and takes a page parameter.
<script type="text/javascript">
function getPageResults( page = 1, arrange = 'next' ) {
$.ajax({
url: url;
type: "POST",
data: "?page=" + page,
success: function(html) {
/* print your info */
if( arrange == 'prev' ) {
$( '#myResults' ).prepend(html);
else if( arrange == 'next' ) {
$( '#myResults' ).append(html);
}
},
error: function(e) {
/* handle your error */
}
});
}
</script>
The HTML View
Your HTML would be fairly basic, just a place to hold your displayed results and some creative triggers.
<html>
<head>
</head>
<body>
<div class="loadPrev"></div>
<div id="myResults">
<!-- Your Results will show up here -->
</div>
<div class="loadNext"></div>
</body>
</html>
Loading the Page You Want
In basic summation, the last piece of your puzzle is loading the page requested based on the querystring in the URL. If no querystring is present, you want page 1. Otherwise, load the requested page.
<script type="text/javascript">
$( document ).ready(function() {
var page = <?php echo ( isset($_GET['page'] ? $_GET['page'] : 1) ?>;
getPageResults( page, 'next' );
});
</script>
After that you can set up some creative listeners for your previous and next triggers and call the getPageResults() with the needed page, and the next or prev attribute as needed.
This can really be done in a much more elegant sense - look at the JS from the example you provided: http://scrollsample.appspot.com/static/main.js
Cleaning it up
Once you have the basic architecture in place, then you can start altering the .pushState() as well as changing out the canonical, next, and prev <link rel> header items. Additionally at this point you can start to generate the next / prev links you need, etc. It should all fall into place once you have that basic foundation laid.
Hey Bro #LionelRitchietheManatee Finnaly I have resolved the problem this is the code that I used.
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
var loaded = true;
$(window).scroll(function(e){
if(($(window).scrollTop() + $(window).height() == $(document).height())&&(loaded)) {
loaded = !loaded;
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
loaded = !loaded;
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
loaded = !loaded;
$(window).scrollTop(60);
});
});
});
}
});
</script>
I had added a new var called "loaded" with initial value as TRUE, and it will be updated to FALSE state when content is loaded, and to the TRUE state when we begin scrolling.
I'ts very primitive as solution not very clean work as you did but it solved my problem.
Thank you anyway for your help, you are the BOSS.
I am working on an infinite scroll (load data on scroll) plugin for my site.
This is the load.js script:
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : 'No More Posts!', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = 'Scroll for more or click here';
else $initmessage = 'Click for more';
// Append custom messages and extra UI
$this.append('<div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('ajax.php', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('#container123').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('Lade...');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
This upper script posts data to a php file called ajax.php, which looks like this (shortened):
$sql = "SELECT * FROM table WHERE";
if (!empty($_GET['search'])){
$sql = $sql . " (Name LIKE '%".$_GET['search']."%' OR Description LIKE '%".$_GET['search']."%')";
} else {
$sql = $sql . " Name!=''";
}
$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
$sql = $sql . " LIMIT ".$postnumbers." OFFSET ".$offset;
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
echo 'item';
}
This ajax.php - script, on the other hand, displays the data in my index.php file.
And here's where the problem is:
Please take a look at the upper if (!empty($_GET['search'])) - statement. Obviously, this $_GET-variable cannot be filled, since the corresponding forms (search-form) are located in my index.php - page.
Now my question is: How can I get the if (!empty($_GET['search'])) to work? I am really not good with ajax, and I believe the problem is that the data created in load.js gets posted to ajax.php in the first place.
Just for completion, this is the corresponding markup in index.php
<section id="start" class="...">
<div id="container123" class="...">
</div>
</section>
<!-- search form etc. -->
Thank you very much in advance. I know it is quite a lot of code. (btw, I know, MySQL is outdated and dangerous)
Modify your plugin to accept search term as parameter and code your index.php something like.
<script>
$("#container123" ).scrollPagination ({ q:'<?php echo $_GET['search']; ?>'"}); </script>
<div id="container123"></div>
Now since this code is written in index.php you will get $_GET['search']
I'm developing a mobile site with endless scrolling to display its content. The endless scrolling is achieved with this script (my implementation of it is below). The script works as it's supposed to.
But some of the content are categorized into different types. On the desktop version without endless scrolling, the types are filtered using the GET method. However, since the actual php for connecting to the database is stored on a separate "ajax.php", the filter parameters contained in GET is not being passed to it, resulting in the ajax.php returning nothing. Is there are way to fix this? Thanks in advance
Page for displaying every:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="javascript.js"></script>
<script>
$(document).ready(function() {
$('#content').scrollPagination({
nop : 5, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : ' ', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
});
});
</script>
</head>
<body>
<div id="content">
<!-- infinite scroll content here -->
</div>
</body>
</html>
javascript.js:
(function($) {
$.fn.scrollPagination = function(options) {
var settings = {
nop : 10, // The number of posts per scroll to be loaded
offset : 0, // Initial offset, begins at 0 in this case
error : ' ', // When the user reaches the end this is the message that is
// displayed. You can change this if you want.
delay : 500, // When you scroll down the posts will load after a delayed amount of time.
// This is mainly for usability concerns. You can alter this as you see fit
scroll : true // The main bit, if set to false posts will not load as the user scrolls.
// but will still load if the user clicks.
}
// Extend the options so they work with the plugin
if(options) {
$.extend(settings, options);
}
// For each so that we keep chainability.
return this.each(function() {
// Some variables
$this = $(this);
$settings = settings;
var offset = $settings.offset;
var busy = false; // Checks if the scroll action is happening
// so we don't run it multiple times
// Custom messages based on settings
if($settings.scroll == true) $initmessage = '顯示更多';
else $initmessage = '顯示更多';
// Append custom messages and extra UI
$this.append('<div class="content"></div><div class="loading-bar">'+$initmessage+'</div>');
function getData() {
// Post data to ajax.php
$.post('ajax.php', {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
// Change loading bar content (it may have been altered)
$this.find('.loading-bar').html($initmessage);
// If there is no data returned, there are no more posts to be shown. Show error
if(data == "") {
$this.find('.loading-bar').html($settings.error);
}
else {
// Offset increases
offset = offset+$settings.nop;
// Append the data to the content div
$this.find('.content').append(data);
// No longer busy!
busy = false;
}
});
}
getData(); // Run function initially
// If scrolling is enabled
if($settings.scroll == true) {
// .. and the user is scrolling
$(window).scroll(function() {
// Check the user is at the bottom of the element
if($(window).scrollTop() + $(window).height() > $this.height() && !busy) {
// Now we are working, so busy is true
busy = true;
// Tell the user we're loading posts
$this.find('.loading-bar').html('載入中...');
// Run the function to fetch the data inside a delay
// This is useful if you have content in a footer you
// want the user to see.
setTimeout(function() {
getData();
}, $settings.delay);
}
});
}
// Also content can be loaded by clicking the loading bar/
$this.find('.loading-bar').click(function() {
if(busy == false) {
busy = true;
getData();
}
});
});
}
})(jQuery);
ajax.php:
<?php
mysql_connect('host', 'username', 'password') or die();
mysql_select_db('database');
#START enable chinese encoding
mysql_query("SET character_set_results=utf8");
#END enable chinese encoding
$offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die();
$postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die();
$category = mysql_real_escape_string($_GET['category']);
$run = mysql_query("SELECT * FROM table WHERE category='$category' ORDER BY date DESC LIMIT ".$postnumbers." OFFSET ".$offset);
while($row = mysql_fetch_array($run)) {
echo '
<a href="/video/video.php?id=' . $row['id'] . '&relatedgroup=' . $row['relatedgroup'] . '">
<div id="contentitemwrap">
<div id="videostripe"> </div>
<div id="contentitemtitle">
<h2>' . $row['name'] . ' <span class="relatedtype">(' . $row['relatedtype'] . ')</span></h2>
於' . $row['date'] . '發表
<p class="contenttext">' . $row['fbdescription'] . '</p>
</div>
<div id="widescreenimagewrap">
<div id="widescreenimageratio">
</div>
<div id="widescreenimage">
<img id="img100" src="' . $row['thumbnail'] . '" />
</div>
</div>
</div>
</a>
';
}
?>
Assuming you are getting the parameters you want to passed into the hosting page via a query string then you should be able to change your $.post call in getData to:
$.post('ajax.php'+window.location.search, {
action : 'scrollpagination',
number : $settings.nop,
offset : offset,
}, function(data) {
..... the rest of your code
I am submitting some data to my database then reloading the same page as the user was just on, I was wondering if there is a way to remember the scroll position the user was just on?
I realized that I had missed the important part of submitting, so, I decided to tweak the code to store the cookie on click event instead of the original way of storing it while scrolling.
Here's a jquery way of doing it:
jsfiddle ( Just add /show at the end of the url if you want to view it outside the frames )
Very importantly, you'll need the jquery cookie plugin.
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When a button is clicked...
$('#submit').on("click", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
Here's still the code from the original answer:
jsfiddle
jQuery:
// When document is ready...
$(document).ready(function() {
// If cookie is set, scroll to the position saved in the cookie.
if ( $.cookie("scroll") !== null ) {
$(document).scrollTop( $.cookie("scroll") );
}
// When scrolling happens....
$(window).on("scroll", function() {
// Set a cookie that holds the scroll position.
$.cookie("scroll", $(document).scrollTop() );
});
});
#Cody's answer reminded me of something important.
I only made it to check and scroll to the position vertically.
(1) Solution 1:
First, get the scroll position by JavaScript when clicking the submit button.
Second, include this scroll position value in the data submitted to PHP page.
Third, PHP code should write back this value into generated HTML as a JS variable:
<script>
var Scroll_Pos = <?php echo $Scroll_Pos; ?>;
</script>
Fourth, use JS to scroll to position specified by the JS variable 'Scroll_Pos'
(2) Solution 2:
Save the position in cookie, then use JS to scroll to the saved position when page reloaded.
Store the position in an hidden field.
<form id="myform">
<!--Bunch of inputs-->
</form>
than with jQuery store the scrollTop and scrollLeft
$("form#myform").submit(function(){
$(this).append("<input type='hidden' name='scrollTop' value='"+$(document).scrollTop()+"'>");
$(this).append("<input type='hidden' name='scrollLeft' value='"+$(document).scrollLeft()+"'>");
});
Than on next reload do a redirect or print them with PHP
$(document).ready(function(){
<?php
if(isset($_REQUEST["scrollTop"]) && isset($_REQUEST["scrollLeft"]))
echo "window.scrollTo(".$_REQUEST["scrollLeft"].",".$_REQUEST["scrollTop"].")";
?>
});
Well, if you use _targets in your code you can save that.
Or, you can do an ajax request to get the window.height.
document.body.offsetHeight;
Then drop them back, give the variable to javascript and move the page for them.
To Remember Scroll all pages Use this code
$(document).ready(function (e) {
let UrlsObj = localStorage.getItem('rememberScroll');
let ParseUrlsObj = JSON.parse(UrlsObj);
let windowUrl = window.location.href;
if (ParseUrlsObj == null) {
return false;
}
ParseUrlsObj.forEach(function (el) {
if (el.url === windowUrl) {
let getPos = el.scroll;
$(window).scrollTop(getPos);
}
});
});
function RememberScrollPage(scrollPos) {
let UrlsObj = localStorage.getItem('rememberScroll');
let urlsArr = JSON.parse(UrlsObj);
if (urlsArr == null) {
urlsArr = [];
}
if (urlsArr.length == 0) {
urlsArr = [];
}
let urlWindow = window.location.href;
let urlScroll = scrollPos;
let urlObj = {url: urlWindow, scroll: scrollPos};
let matchedUrl = false;
let matchedIndex = 0;
if (urlsArr.length != 0) {
urlsArr.forEach(function (el, index) {
if (el.url === urlWindow) {
matchedUrl = true;
matchedIndex = index;
}
});
if (matchedUrl === true) {
urlsArr[matchedIndex].scroll = urlScroll;
} else {
urlsArr.push(urlObj);
}
} else {
urlsArr.push(urlObj);
}
localStorage.setItem('rememberScroll', JSON.stringify(urlsArr));
}
$(window).scroll(function (event) {
let topScroll = $(window).scrollTop();
console.log('Scrolling', topScroll);
RememberScrollPage(topScroll);
});
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>
I tackle this via using window.pageYOffset . I saved value using event listener or you can directly call window.pageYOffset. In my case I required listener so it is something like this:
window.addEventListener('scroll', function() {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
})
And I save latest scroll position in localstorage. So when next time user comes I just check if any scroll value available via localstorage if yes then scroll via window.scrollTo(0,myScrollPos)
sessionStorage.setItem("VScroll", $(document).scrollTop());
var scroll_y = sessionStorage.getItem("VScroll");
setTimeout(function() {
$(document).scrollTop(scroll_y);
}, 300);