Infinite Scroll with history.pushState - php

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.

Related

load new content on scroll

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']

unable to write javascript inside the php page

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

Using Colorbox and a javascript function

I'm trying to display a hyperlink that has a colorbox popup associated with it.
The javascript is:
function bid() {
var bid = document.getElementById("bid").value;
if (bid>0 && bid<=100) {
var per = 3.50;
} else if (bid>100 && bid<=200) {
var per = 3.40;
} else if (bid>200 && bid<=300) {
var per = 3.30;
}
var fee = Math.round(((bid/100)*per)*100)/100;
var credit = 294.9;
if (fee>credit) {
var message = 'Error';
} else {
var message = '<a class="popup" href="URL">The link</a>';
}
document.getElementById("bidText").innerHTML=message;
}
The javascript works fine and displays the link in the right conditions, the problem however is that when clicking the link, the Colorbox isn't being applied and the page loads as a normal hyperlink.
I have the following code in the header:
jQuery(document).ready(function () {
jQuery('a.popup').colorbox({ opacity:0.5 , rel:'group1' });
});
If I output just the hyperlink in the standard html source, it works fine and displays correctly in the Colorbox.
Any help would be greatly appreciated :)
You need to wait until you've appended the link before you call the colorbox() method on it.
Move your colorbox() method so that it comes after your innerHTML.
jQuery('a.popup').colorbox({ opacity:0.5 , rel:'group1' });
when adding html dynamically you, the event added already can not be triggered.
try the following code
jQuery(document).ready(function () {
$("a.popup").on("click", function(event){
applycolorbox($(this));
});
function applycolorbox($elem) {
$elem.colorbox({ opacity:0.5 , rel:'group1' });
}

how to remember scroll position of page

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

Use Jquery to update a PHP session variable when a link is clicked

I have several divs that a user can Minimize or Expand using the jquery toggle mothod. However, when the page is refreshed the Divs go back to their default state. Is their a way to have browser remember the last state of the div?
For example, if I expand a div with an ID of "my_div", then click on something else on the page, then come back to the original page, I want "my_div" to remain expanded.
I was thinking it would be possible to use session variables for this, perhaps when the user clicks on the expand/minimize button a AJAX request can be sent and toggle a session variable...IDK..any ideas?
There's no need for an ajax request, just store the information in a cookie or in the localstorage.
Here's a library which should help you out: http://www.jstorage.info/
Some sample code (untested):
// stores the toggled position
$('#my_div').click(function() {
$('#my_div').toggle();
$.jStorage.set('my_div', $('#my_div:visible').length);
});
// on page load restores all elements to old position
$(function() {
var elems = $.jStorage.index();
for (var i = 0, l = elems.length; i < l; i++) {
$.jStorage.get(i) ? $('#' + i).show() : hide();
}
});
If you don't need to support old browsers, you can use html5 web storage.
You can do things like this (example taken from w3schools):
The following example counts the number of times a user has visited a
page, in the current session:
<script type="text/javascript">
if (sessionStorage.pagecount) {
sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;
}
else {
sessionStorage.pagecount=1;
}
document.write("Visits "+sessionStorage.pagecount+" time(s) this session.");
</script>
Others have already given valid answers related to cookies and the local storage API, but based on your comment on the question, here's how you would attach a click event handler to a link:
$("#someLinkId").click(function() {
$.post("somewhere.php", function() {
//Done!
});
});
The event handler function will run whenever the element it is attached to is clicked. Inside the event handler, you can run whatever code you like. In this example, a POST request is fired to somewhere.php.
I had something like this and I used cookies based on which user logged in
if you want only the main div don't use the
$('#'+div_id).next().css('display','none');
use
$('#'+div_id).css('display','none');
*Here is the code *
//this is the div
<div id = "<?php echo $user; ?>1" onclick="setCookie(this.id)" ><div>My Content this will hide/show</div></div>
function setCookie(div_id)
{
var value = '';
var x = document.getElementById(div_id);
var x = $('#'+div_id).next().css('display');
if(x == 'none')
{
value = 'block';
}
else
{
value = 'none';
}
console.log(div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/")
//alert(x);
document.cookie = div_id+"="+value+"; expires=15/02/2012 00:00:00;path=/";
}
function getCookie(div_id)
{
console.log( div_id );
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==div_id)
{
return unescape(y);
}
}
}
function set_status()
{
var div_id = '';
for(var i = 1; i <= 9 ; i++)
{
div_id = '<?php echo $user; ?>'+i;
if(getCookie(div_id) == 'none')
{
$('#'+div_id).next().css('display','none');
}
else if(getCookie(div_id) == 'block')
{
$('#'+div_id).next().slideDown();
}
}
}
$(document).ready(function(){
get_status();
});
Look about the JavaScript Cookie Method, you can save the current states of the divs, and restore it if the User comes back on the Site.
There is a nice jQuery Plugin for handling Cookies (http://plugins.jquery.com/project/Cookie)
Hope it helps
Ended up using this. Great Tutorial.
http://www.shopdev.co.uk/blog/cookies-with-jquery-designing-collapsible-layouts/

Categories