Reinitializing jScroll after AJAX call? (Still loading old href after AJAX load) - javascript

I'm paginating search results returned from an AJAX call with jScroll:
$('#search').keyup(function() {
var search = $(this).val();
$.get('/search', {search : search}, function(results) {
$('.scroll-table').html(results);
$('.scroll-table').jscroll();
});
});
After making a new search, when I scroll to the bottom, jScroll loads the content of the last href for the old search.
So if my old _nextHref was /search?query=A&page=3 and I enter B in the search field, instead of loading /search?query=B&page=2 from the new href, it will load /search?query=A&page=3 from the old href.
Apparently calling jscroll() from the ajax success function won't reconstruct it and _nextHref stays set to its old value. I tried destroying it before loading it, but it will keep it fom loading altogether:
$('#search').keyup(function() {
var search = $(this).val();
$('.scroll-table').jscroll.destroy();
$.get('/search', {search : search}, function(results) {
$('.scroll-table').html(results);
$('.scroll-table').jscroll(); /* now jScroll won't load at all */
});
});
Can you please give me an example how to reinitialize jScroll so it loads the new href?

I found a temporary solution by commenting out the following line:
// if (data && data.initialized) return;
This caused a further problem.. If the result list fits a single page (no pagination needed so there is no href on the first page, "Loading..." is displayed on the bottom of the list, because jScroll wanted to GET "/undefined" from the server. Here is how i fixed it:
// Initialization
if (_nextHref != 'undefined') {
$e.data('jscroll', $.extend({}, _data, {initialized: true, waiting: false, nextHref: _nextHref}));
_wrapInnerContent();
_preloadImage();
_setBindings();
} else {
_debug('warn', 'jScroll: nextSelector not found - destroying');
_destroy();
return false;
}
I don't know if there is a better way to do this, but now it works with AJAX calls as I expect it to work. If anyone knows of a proper way to reinitialize the plugin, please share it with us.
UPDATE: I created a proper fork of jScroll allowing it to be reinitialized on each AJAX load, preventing it from loading the old href, using:
$('.scroll').jscroll({
refresh: true
});
Hopefully this functionality gets merged in the main version.

If you don't want to patch jScroll, you can clear the jScroll data in your load (or get) callback:
var pane = $('#myInfiniteScroll');
pane.load(url, function() {
pane.data('jscroll', null);
pane.jscroll({
nextSelector: "link[rel='next']",
autoTrigger: true,
});
});
When you call the jscroll function, pass the same parameters as when you first initialized it (in this example, I defined two configuration parameters, but use what you need.). Better yet, factor that out into its own function so you don't end up duplicating code.

Related

DOM elements manipulation with javascript persists after reload or going to next page in pagination

I am trying to toggle a view between grid and list view mode on my frontend HTML page. I am able to do this fine with dom and HTML classes manipulation by toggling "display: none" between two containers. However, when I go to the next product page(through pagination) or when I reload the page, the default view is the one that appears and not the one that was last toggled. Is there a way to persist the view in case a page reload or product pagination changes? thank you.
here is the dom code that achieves this :
viewList.addEventListener('click', function() {
this.classList.add('view__active');
viewGrid.classList.remove('view__active');
gridItem.classList.add('hidden');
listItem.classList.remove('hidden');
});
viewGrid.addEventListener('click', function() {
this.classList.add('view__active');
viewList.classList.remove('view__active');
gridItem.classList.remove('hidden');
listItem.classList.add('hidden');
});
So far I found that I have to use localStorage to achieve this. but is there a better way to do this?
Essentially what is happening is when you request something from the server, the server responds with an HTML document, and whichever scripts associated with that document is run, So whatever JS executed in the first request is not in context when the second request(paginate or reload) is made.
So you need a way to persist information across these page loads, For that, you have 3 options.
Use sessionStorage.
Use localStorage
Use Cookies.
Of the 3 above the easiest would be to use either option 1 or 2.
Replying to your comment,
Also, If I am using localStorage, What am I using to store the view state?
I'm not quite clear as to what you mean by "What you are using to store the state" If your question is about where your data is stored, you need not worry about it as this is handled by the browser. If your question is about "How" to store it you can go through the MDN docs attached in option 1 or 2. This is simply storing a key-value pair as shown in the docs
localStorage.setItem('preferedView', 'grid'); You can add this to your on click handlers as follows,
viewList.addEventListener('click', function() {
this.classList.add('view__active');
viewGrid.classList.remove('view__active');
gridItem.classList.add('hidden');
listItem.classList.remove('hidden');
localStorage.setItem('preferedView', 'grid');
});
viewGrid.addEventListener('click', function() {
this.classList.add('view__active');
viewList.classList.remove('view__active');
gridItem.classList.remove('hidden');
listItem.classList.add('hidden');
localStorage.setItem('preferedView', 'list');
});
Then when loading a new page at the top of your script you can get the users preferedView(if existing) via const preferedView = localStorage.getItem('preferedView');
Here is a complete example from MDN
In order for anyone to find an answer for a similar task, thanks to #Umendra insight, I was able to solve this by using this :
function viewToggeler(viewBtn1, viewBtn2, view1, view2, viewStord) {
viewBtn2.classList.add('view__active');
viewBtn1.classList.remove('view__active');
view1.classList.add('hidden');
view2.classList.remove('hidden');
sessionStorage.setItem('preferedView', viewStord);
}
viewList.addEventListener('click', () => {
viewToggeler(viewGrid, viewList, gridItem, listItem, 'list');
});
viewGrid.addEventListener('click', () => {
viewToggeler(viewList, viewGrid, listItem, gridItem, 'grid');
});
if (sessionStorage.getItem('preferedView') === 'grid') {
viewToggeler(viewList, viewGrid, listItem, gridItem, 'grid');
} else if (sessionStorage.getItem('preferedView') === 'list') {
viewToggeler(viewGrid, viewList, gridItem, listItem, 'list');
}
I ended up using sessionStorage over localStorage because it empties itself on window/tab closing which might be the most desirable result. localStorage persists even after exiting the browser and opening it back.
Also, at any point someone wants to empty the sessionStorage on exit, I used :
window.addEventListener('onbeforeunload', () => {
sessionStorage.removeItem('preferedView');
});

Destroying InfiniteScroll on AJAX page change

We have a website that is running jQuery Infinite Scroll Plugin. The plugin is no longer maintained but it is the only one that really serves our purpose properly. However, the problem I have is that our site is ajax based. On page change the pg-changed trigger is fired against the window, which allows us to check if the Infinite Scroll container is there and enable Infinite Scroll. If the Infinite Scroll container isn't there but $.infscr exists, we will attempt to destroy the previous instance.
The problem I am having is that when changing to another page, it doesn't seem to be getting destroyed properly and sometimes AJAX calls will be made, along with the infscr loading bar displaying. Here is the code I am using to instantiate and destroy the plugin:
$(window).on('pg-changed', function () {
// delete our infinite scroll
if(typeof $.infscr !== 'undefined') {
$('.snap-inner, .infscr').data('infinitescroll', null);
$('.snap-inner, .infscr').infinitescroll('unbind');
$('.snap-inner, .infscr').infinitescroll('destroy');
$('#infscr-loading').remove();
$.infscr.data('infinitescroll', null);
$.infscr.infinitescroll('unbind');
$.infscr.infinitescroll('destroy');
delete $.infscr;
}
// setup our infinite scroll
if($('.infscr').length) {
$.infscr = $('.infscr').infinitescroll({
// define our navigation selectors
navSelector : 'div.infscr-navigation',
nextSelector : 'div.infscr-navigation A:first',
itemSelector : '.infscr-item',
// allow scrolling an overflowed element
behavior : 'local',
bufferPx : 120,
binder : $('.snap-inner'),
dataType : 'html',
loading : {
msg : null,
selector : '.snap-content',
img : 'data:image/gif;base64,TRIMMED',
msgText : '<span class="infscr-loading">Loading...</span>',
}
}, function (arrayOfNewElems) {
// render background images on our new elements
$(this).renderBgImages();
});
}
});
I really hope you can help with this as it has become quite a problem now, firing on scroll, making AJAX calls and displaying the loading bar.
I guess the problem might be that the plugin binds events on elements external to itself. It's hard to say without further debugging (is the plugin deleted or does it fail to do so?). If it does, why would it fail to unbind the events? etc.
When you say, 'on another page', I suppose you are not loading a whole new page (which would 'reset' the javascript.
Though, depending on wether this could work for you, you might want to try unbinding ALL events on the document, and starting fresh.
$(document).add('*').off();
should do so. If it does, you could try to pinpoint what elements/events you need to unbind manually. Let me know if this works or not.

jQuery - bxSlider plugin reloadSlider issues

I'm using jQuery with the bxSlider plugin, here is the link to it just incase: http://bxslider.com/
I'm trying to reload the slider and my custom pager after I've removed certain slides from it.
Here is what I have tried:
$(function() {
var slider = $('#slider').bxSlider({
pagerCustom: '#bx-pager'
});
$('.list').on('click', '.delete', function() {
image = $(this).closest('li').find('[type="hidden"]');
// image.attr('id') contains a string: image-0, image-1, image-2, etc.
$('#slider, #bx-pager').find('.' + image.attr('id')).remove();
slider.reloadSlider({
pagerCustom: '#bx-pager'
}); // I have also tried: slider.reloadSlider();
});
});
It works partially. What happens is the slider gets reloaded just fine but it removes the pager completely when it runs the reload.
Thank you very much for any help.
As long as I see, this is a bug in bxSlider, in fact, when you call the reloadSlider method, internally are called the methods destroySlider and init.
In the destroySlider method the pagerEl element is destroyed, this is right if you are not using a custom one, because it is recreated programmatically in the init method, but if you are using a custom one it can't be recreated programmatically.
I ended up modifying the destroySlider method to check if a custom pager is used, in this case it must not be deleted.
Here is the before (line 1294):
if(slider.pagerEl) slider.pagerEl.remove();
And after:
if (slider.settings.pagerCustom === '') {
if(slider.pagerEl) slider.pagerEl.remove();
}
I'll post the bug on GitHub as soon as I have the time.

Which is proper listener to use doLayout function?

I am working in EXTJs, Please check below example:
var containerForm=Ext.widget('panel',{
width: 1100,
border: false,
frame: true,
"layout":"fit",
title: 'Add User',
hidden:true,
listeners:{
'afterrender': function(panelObj,eOpts )
{
panelObj.doLayout();
}
}
});
Html of above panel is updating via ajax response as shown in the following code:
formObj.update(jsonResp.html,true,function(){
containerForm.doLayout();containerForm.focus();
});
containerForm is auto height panel, because this panel is used for multiple pupose,
When "formObj.update" populating this panel content, it's content loading properly but
If ajax response "jsonResp.html" has any image, that time doLayout() function is not helping to align panel height properly,
i added doLayout function at 2 places but callback function is not helping me in above case:
when i call doLayout function after 2 seconds then only it's work correctly:
formObj.update(jsonResp.html,true,function(){
setTimeout('containerForm.doLayout(); containerForm.focus();', 2000);
});
Which is proper listener to use doLayout function?
You could take a look at the Mutation Events but these are not cross browser compatible. If they were, you could try:
formObj.on('DOMSubtreeModified', function(){containerForm.doLayout();}, this);
You really just need to make sure your formObj.update() is complete. That is why your timeout is helping. If you want to make sure the innerHtml is set, just check it yourself.
If you look at the Source for Ext.dom.Element.update(), it is just using dom.innerHtml to update the html. In your update callback, you could check to see if the innerHtml is there before calling doLayout(). Some simple example code I threw together quick.
var doLayoutIfComplete = function(){
if(document.getElementById('formObjId').innerHTML == jsonResp.html){
containerForm.doLayout();
}
else{
doLayoutWhenComplete.delay(500); //Check again in 500ms
}
}
var doLayoutWhenComplete = new Ext.util.DelayedTask(function(){
doLayoutIfComplete();
});
formObj.update(jsonResp.html,true,function(){
doLayoutWhenComplete.delay(500);
});

Single paged website, which i want to get at a certain point after refreshing page

I have a single paged website, in which i've got a div named sitecontent with the width of 4400, which holds 4 "pages". The pages start at 0px of sitecontent, 1100 px of sitecontent, 2200px of sitecontent, and 3300px.
I use Jquery to set de div position to the right px, so i get the right text displayed. After pressing a link i get for example:
<div id="site-content" style="left: -1100px;">
At one of the pages i have to refresh the page, and after this refresh i want the page to display the same "page" on 1100px, but it starts at 0px, the home page.
Is there any way how i can make sure that the sitecontent starts at -1100px of home?
Thanks in advance,
Cheers
You need to append some identifier onto the hash of the URL that you can parse on the page load.
For example:
http://www.somewebpage.com/somepage#page1
Then in the load of the page, you can inspect this hash value and immediately change the UI to show the new page:
var hash = window.location.hash;
if(hash == "#page1")
$('#site-content').css('left', '-1100px');
You can use a cookie to store the value, then, every time the page loads, you need to check the cookie and deal with the value collected:
The link for Jquery Cookie with download and usage manual!
HTML (example)
<a href="#" title="Go Page 1" id="page_01" class="setCookie">
Click to view page 01
</a>
JQUERY (jquery.cookie)
// SET THE COOKIE
$('.setCookie').bind("click", function() {
var pageNumber = $(this).attr("id");
$.cookie('the_cookie_name', pageNumber, { expires: 7, path: '/' });
});
// READ THE COOKIE
$(function() {
var oldNumber = $.cookie('the_cookie_name');
if (oldNumber !== NULL) {
$("#page_"+oldNumber).trigger("click");
}
});
Note:
The link that you currently use to change pages, should have the class "setCookie" to trigger the cookie creation, and also the id that is being used to identify the page number.
One advantage of this is that you can control for how long is the cookie preserved and thus allowing the visitant to resume the website experience.
An approach very similar to what Tejs is proposing would be to use a hash-based routing framework that listens to hash changes. That will result in much cleaner code since you don't need to define the scrolling in two different places.
Every link in your page is currently being observed by a jQuery event listener (onclick -> moves the content container to the show the desired content). The HTML looks probably somewhat like this: Contact details.
With this approach, you don't need to watch those links. Instead, simply make them change the hash: Contact details.
Now observe the hash and react to changes. I'm using the Simrou framework (https://github.com/buero-fuer-ideen/Simrou) but you can go with any other framework that provides similar functionality.
jQuery(document).ready(function() {
// Define a function that moves the content, e.g. moveContent(3300);
function moveContent(pixelPosition) {
$('#site-content').css('left', '-' + pixelPosition + 'px');
}
// Setup the router
var router = new Simrou({
'page1': function() { moveContent(0); },
'page2': function() { moveContent(1100); },
'page3': function() { moveContent(2200); },
'page4': function() { moveContent(3300); }
});
router.start();
});
That's all the javascript you need!
(and here is a quick and dirty fiddle, demonstrating the whole thing: http://jsfiddle.net/R7F6r/)

Categories

Resources