jquery/ajax infinite scroll event - javascript

I'm trying to make my own infinite scroll using ajax, php, mysql on my web app. However I can't find a way to load the new content each time the user is a the end of the page.
For now it loads all the data as soon as the user hit the end of the page.
Is there any way to make my script 'wait until the end of the last page loaded'.
$( ".places-wrapper ").scroll(function(){
var windowHeight = $( ".places-wrapper" ).height();
var documentHeight = $( ".places-wrapper")[0].scrollHeight;
var scrollFromTop = $( ".places-wrapper" ).scrollTop();
var margin = 70;
if( scrollFromTop >= documentHeight - windowHeight - margin){
loadNextPage();
}
function loadNextPage(){
var PlaceID = $( "input[name='placeID']:last" ).val();
var lastHitDate = $( "input[name='hitDate']:last" ).val();
$.ajax({
# .append the new stuff
});
}
});

I guess what you need is a flag to tell your script that a page is loading.
You may try this approach:
// add a variable as flag
var isLoading = false;
if( scrollFromTop >= documentHeight - windowHeight - margin){
if ( !isLoading )
{
isLoading = true;
loadNextPage();
}
}
// inside your ajax's success callback:
.success(function(){
isLoading = false;
// add the page contents
})

As you propably guessed you need an external variable that turns the "load further places"-switch on and off.
var scrollActiveTimer = false;
$(".places-wrapper").scroll(function(){
// Don't continue if a previous ajax request is still active
if(scrollActiveTimer == true){
return;
}
// For an improved performance you should try to minimize the jquery DOM searches
var wrapper = $(".places-wrapper");
var windowHeight = wrapper.height();
var documentHeight = wrapper[0].scrollHeight;
var scrollFromTop = wrapper.scrollTop();
var margin = 70;
var scrollEndPosition = documentHeight - windowHeight - margin;
if( scrollFromTop >= scrollEndPosition){
loadNextPage();
}
function loadNextPage(){
// Disable the loading of further pages for the moment
scrollActiveTimer = true;
var PlaceID = $("input[name='placeID']:last").first().val();
var lastHitDate = $( "input[name='hitDate']:last" ).val();
// Activate the loading event again
scrollActiveTimer = false;
$.ajax({
// parameters..
}).success(function(data){
// copy data into html
wrapper.append(data);
// Activate the loading event again
scrollActiveTimer = false;
});
}
});
I made a fiddle with some dummy functions to simulate the ajax request and html generation: http://jsfiddle.net/Macavity/f77xmho7/2/

Related

Triggering an Immediately resize with jQuery

so I made a little code with jQuery ( not the best jquery user yet. )
$(function(){
var theDiv = $('.blury-format-image .post-info .title');
var theThumbnail = $('.blury-format-image .thumbnail').innerHeight();
var theThumbnailW = $('.blury-format-image .thumbnail').innerWidth();
theDiv.innerHeight( theThumbnail );
theDiv.innerWidth( theThumbnailW );
});
which just resizes the div as the height and width of the thumbnail, anyway it only works when I refresh the page which is a problem! because if a mobile user tried the landscape mode the dimensions will look really bad!
is there's somehow to trigger it immediately with any resize action? ty.
Make this as separeate Function called ResizeDiv
function ResizeDiv(){
var theDiv = $('.blury-format-image .post-info .title');
var theThumbnail = $('.blury-format-image .thumbnail').innerHeight();
var theThumbnailW = $('.blury-format-image .thumbnail').innerWidth();
theDiv.innerHeight( theThumbnail );
theDiv.innerWidth( theThumbnailW );
};
<script>
$(function(){
ResizeDiv(); //would be called on page Refresh
})
$(window).on('resize',function(){
ResizeDiv(); // this would be called on resize event
})
</script>
because
$(function(){
is like $(document).ready()
Any code directly inside will be called on document gets ready..which only happens on page refresh... hence you now know why it works only on page refresh
ref : https://api.jquery.com/resize/
$(function()
rez();
$(window).resize(function() {
rez();
});
});
function rez(){
var theDiv = $('.blury-format-image .post-info .title');
var theThumbnail = $('.blury-format-image .thumbnail').innerHeight();
var theThumbnailW = $('.blury-format-image .thumbnail').innerWidth();
theDiv.innerHeight( theThumbnail );
theDiv.innerWidth( theThumbnailW );
}

ajaxify-html5.js reload only part of the page?

I found the following script online that makes your website load content with AJAX.
Everything works fine, but it also reload my music player that has to stay when clicking a link.
// Ajaxify
// v1.0.1 - 30 September, 2012
// https://github.com/browserstate/ajaxify
(function(window,undefined){
// Prepare our Variables
var
History = window.History,
$ = window.jQuery,
document = window.document;
// Check to see if History.js is enabled for our Browser
if ( !History.enabled ) {
return false;
}
// Wait for Document
$(function(){
// Prepare Variables
var
/* Application Specific Variables */
contentSelector = '#content,article:first,.article:first,.post:first',
$content = $(contentSelector).filter(':first'),
contentNode = $content.get(0),
$menu = $('#menu,#nav,nav:first,.nav:first').filter(':first'),
activeClass = 'active selected current youarehere',
activeSelector = '.active,.selected,.current,.youarehere',
menuChildrenSelector = '> li,> ul > li',
completedEventName = 'statechangecomplete',
/* Application Generic Variables */
$window = $(window),
$body = $(document.body),
rootUrl = History.getRootUrl(),
scrollOptions = {
duration: 800,
easing:'swing'
};
// Ensure Content
if ( $content.length === 0 ) {
$content = $body;
}
// Internal Helper
$.expr[':'].internal = function(obj, index, meta, stack){
// Prepare
var
$this = $(obj),
url = $this.attr('href')||'',
isInternalLink;
// Check link
isInternalLink = url.substring(0,rootUrl.length) === rootUrl || url.indexOf(':') === -1;
// Ignore or Keep
return isInternalLink;
};
// HTML Helper
var documentHtml = function(html){
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>')
;
// Return
return $.trim(result);
};
// Ajaxify Helper
$.fn.ajaxify = function(){
// Prepare
var $this = $(this);
// Ajaxify
$this.find('a:internal:not(.no-ajaxy)').click(function(event){
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = $this.attr('title')||null;
// Continue as normal for cmd clicks etc
if ( event.which == 2 || event.metaKey ) { return true; }
// Ajaxify this link
History.pushState(null,title,url);
event.preventDefault();
return false;
});
// Chain
return $this;
};
// Ajaxify our Internal Links
$body.ajaxify();
// Hook into State Changes
$window.bind('statechange',function(){
// Prepare Variables
var
State = History.getState(),
url = State.url,
relativeUrl = url.replace(rootUrl,'');
// Set Loading
$body.addClass('loading');
// Start Fade Out
// Animating to opacity to 0 still keeps the element's height intact
// Which prevents that annoying pop bang issue when loading in new content
$content.animate({opacity:0},800);
// Ajax Request the Traditional Page
$.ajax({
url: url,
success: function(data, textStatus, jqXHR){
// Prepare
var
$data = $(documentHtml(data)),
$dataBody = $data.find('.document-body:first'),
$dataContent = $dataBody.find(contentSelector).filter(':first'),
$menuChildren, contentHtml, $scripts;
// Fetch the scripts
$scripts = $dataContent.find('.document-script');
if ( $scripts.length ) {
$scripts.detach();
}
// Fetch the content
contentHtml = $dataContent.html()||$data.html();
if ( !contentHtml ) {
document.location.href = url;
return false;
}
// Update the menu
$menuChildren = $menu.find(menuChildrenSelector);
$menuChildren.filter(activeSelector).removeClass(activeClass);
$menuChildren = $menuChildren.has('a[href^="'+relativeUrl+'"],a[href^="/'+relativeUrl+'"],a[href^="'+url+'"]');
if ( $menuChildren.length === 1 ) { $menuChildren.addClass(activeClass); }
// Update the content
$content.stop(true,true);
$content.html(contentHtml).ajaxify().css('opacity',100).show(); /* you could fade in here if you'd like */
// Update the title
document.title = $data.find('.document-title:first').text();
try {
document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
// Add the scripts
$scripts.each(function(){
var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
if ( $script.attr('src') ) {
if ( !$script[0].async ) { scriptNode.async = false; }
scriptNode.src = $script.attr('src');
}
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
// Complete the change
if ( $body.ScrollTo||false ) { $body.ScrollTo(scrollOptions); } /* http://balupton.com/projects/jquery-scrollto */
$body.removeClass('loading');
$window.trigger(completedEventName);
// Inform Google Analytics of the change
if ( typeof window._gaq !== 'undefined' ) {
window._gaq.push(['_trackPageview', relativeUrl]);
}
// Inform ReInvigorate of a state change
if ( typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined' ) {
reinvigorate.ajax_track(url);
// ^ we use the full url here as that is what reinvigorate supports
}
},
error: function(jqXHR, textStatus, errorThrown){
document.location.href = url;
return false;
}
}); // end ajax
}); // end onStateChange
}); // end onDomLoad
})(window); // end closure
Let me explain it a little bit better.
The website has a music player that plays music while you are visiting the website, so clearly the music is not ment to stop whenever you click on a link.
This script works perfectly but it does refresh the whole page (using ajax) AND it is refreshing the music player.
There also is another script that comes with this one for changing the url and title ...
Thanks in advance, Greets
use the statechangecomplete event.
$(window).on('statechangecomplete', function(e, eventInfo){
//your code
})

Modify collapse.js to get addtional data from xml when expanding fieldset in Drupal 7?

In drupal i have generated a list where each item is a fieldset with collapsible, that can contain extra information.
Because of the rather large list i want to avoid loading the extra information until a user clicks on the fieldset.
Best case scenario:
User clicks on collapsed fieldset.
Fieldset loads extra information.
Fieldset uncollapses.
I've copied and loaded the copy of collapse.js into my form, but I'm very new to js and jQuery, so I'm a little lost. If someone can show me how to call a function the first time the fieldset is expanded, I'm sure i can figure out the rest.
I've included the code from collapse.js:
(function ($) {
//Toggle the visibility of a fieldset using smooth animations.
Drupal.toggleFieldset = function (fieldset) {
var $fieldset = $(fieldset);
if ($fieldset.is('.collapsed')) {
var $content = $('> .fieldset-wrapper', fieldset).hide();
$fieldset
.removeClass('collapsed')
.trigger({ type: 'collapsed', value: false })
.find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide'));
$content.slideDown({
duration: 'fast',
easing: 'linear',
complete: function () {
Drupal.collapseScrollIntoView(fieldset);
fieldset.animating = false;
},
step: function () {
// Scroll the fieldset into view.
Drupal.collapseScrollIntoView(fieldset);
}
});
}
else {
$fieldset.trigger({ type: 'collapsed', value: true });
$('> .fieldset-wrapper', fieldset).slideUp('fast', function () {
$fieldset
.addClass('collapsed')
.find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show'));
fieldset.animating = false;
});
}
};
//Scroll a given fieldset into view as much as possible.
Drupal.collapseScrollIntoView = function (node) {
var h = document.documentElement.clientHeight || document.body.clientHeight || 0;
var offset = document.documentElement.scrollTop || document.body.scrollTop || 0;
var posY = $(node).offset().top;
var fudge = 55;
if (posY + node.offsetHeight + fudge > h + offset) {
if (node.offsetHeight > h) {
window.scrollTo(0, posY);
}
else {
window.scrollTo(0, posY + node.offsetHeight - h + fudge);
}
}
};
Drupal.behaviors.collapse = {
attach: function (context, settings) {
$('fieldset.collapsible', context).once('collapse', function () {
var $fieldset = $(this);
// Expand fieldset if there are errors inside, or if it contains an
// element that is targeted by the uri fragment identifier.
var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : '';
if ($('.error' + anchor, $fieldset).length) {
$fieldset.removeClass('collapsed');
}
var summary = $('<span class="summary"></span>');
$fieldset.
bind('summaryUpdated', function () {
var text = $.trim($fieldset.drupalGetSummary());
summary.html(text ? ' (' + text + ')' : '');
})
.trigger('summaryUpdated');
// Turn the legend into a clickable link, but retain span.fieldset-legend
// for CSS positioning.
var $legend = $('> legend .fieldset-legend', this);
$('<span class="fieldset-legend-prefix element-invisible"></span>')
.append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide'))
.prependTo($legend)
.after(' ');
// .wrapInner() does not retain bound events.
var $link = $('<a class="fieldset-title" href="#"></a>')
.prepend($legend.contents())
.appendTo($legend)
.click(function () {
var fieldset = $fieldset.get(0);
// Don't animate multiple times.
if (!fieldset.animating) {
fieldset.animating = true;
Drupal.toggleFieldset(fieldset);
}
return false;
});
$legend.append(summary);
});
}
};
})(jQuery);
It looks to me like you'd have to override the whole Drupal.toggleFieldset function (just like when you are overriding a Drupal theme function.
You could perhaps add a class to the fieldset in FormAPI then catch it in the complete function of the $content.slideDown params and fire a custom function of yours, to add a 'loading' graphic and make your ajax request.
I'm assuming from your question that you are familiar enough with FormAPI/jQuery.ajax() to have a go. But let me know if not and i'll include some snippets
EDIT
Here is some example code, it'd take a quite a while to setup a test environment for this, so it'just a pointer (cant create a JS fiddle for this ;))
You might add your fieldset like this in PHP
$form['my_fieldset'] = array(
'#type' = 'fieldset',
'#title' = t('My fieldset'),
'#collapsible' = true,
'#collapsed' = true,
'#attributes' => array(
'class' => array('ajax-fieldset'),
'rel' => 'callback/url/path' // random attribute to store the link to a menu path that will return your HTML
)
);
$form['my_fieldset'] = array(
'#markup' => '<div class="response">loading...</div>'
);
You'll also obviously have setup a menu hook returning your themed data # callback/url/path. IMO it's better to return JSON data and theme them in with JS templating, but the Drupal way (for the moment at least) seems to be to render HTML in the menu hook callback function.
Then here is the JS. I've only included the altered complete function, rather than reproduce what you pasted. Add the complete function in to a copy of the code the re-specify the core Drupal function in your own JS file
$content.slideDown({
complete: function () {
Drupal.collapseScrollIntoView(fieldset);
fieldset.animating = false;
if($fieldset.hasClass('ajax-fieldset')) {
$.get(
Drupal.settings.basePath + $fielset.attr('rel'),
function(data) {
$fieldset.find('.response').html(data);
}
)
}
}
});
Or, rather than messing around with the collapsible function. just create your own fieldset without the collapsible/collapsed classes and implement from scratch yourself
....so.. something like that :)

How to start optimising/refactoring jQuery code

I have following jQuery code
$('a.editpo, a.resetpass').click(function(event){
event.preventDefault();
var urlToCall = $(this).attr('href');
var hyperlinkid = '#'+$(this).attr('id');
var targetId = $(this).attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = $(this).html();
/*Todo: refactor or shorten the following statement*/
if((currentLink=='Edit' && $('#resetuserpassform_'+targetId).is(':visible'))
||
(currentLink=='Reset Pass' && $('#account-home-container-'+targetId).is(':visible'))
||
($(targetTdDiv).html() =='')
){
$.ajax({
url:urlToCall,
success: function(html){
$(targetTdDiv).html(html);
$(targetTrDiv).show();
}
});
}else{
$(targetTrDiv).hide();
$(targetTdDiv).html('');
}
});
The editpo and resetpass are classes applied on hyperlinks in column of table, namely Edit and Reset Pass, clicking these load up the form in a table row, ids for the respective tr and td is targetTrDiv and targetTdDiv. I am not good at JS and specially jQuery, but would still be interested in any optimisations.
But I am especially interested in reducing the condition statement.
First, you can optimize the following code:
var urlToCall = $(this).attr('href');
var hyperlinkid = '#'+$(this).attr('id');
var targetId = $(this).attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = $(this).html();
to:
var wrappedSet$ = $(this);
var urlToCall = wrappedSet$.attr('href');
var hyperlinkid = '#'+wrappedSet$.attr('id');
var targetId = wrappedSet$.attr('id').match(/\d+/);
var targetTrDiv = '#poformloadertr_'+targetId;
var targetTdDiv = '#poformloadertd_'+targetId;
var currentLink = wrappedSet$.html();
EDIT: Also, you could remove the currentLink=='Edit' && and currentLink=='Reset Pass' && code snippets, because you can be sure that the right links were clicked using the class selector that you are using in your jQuery click handler (a.editpo, a.resetpass).
If you do that the codition statement will stays like this:
if(($('#resetuserpassform_'+targetId).is(':visible'))
||
($('#account-home-container-'+targetId).is(':visible'))
||
($(targetTdDiv).html() =='')
){
/* AJAX call goes here */
}
Besides, and hopefully I'm wrong, it's very unlikely that the condition statement can be more optimized. The reason for concluding this is that you want to much specificity that is likely impossible to achieve in other way.
Hope it helps you.

jQuery trigger action when a user scrolls past a certain part of the page

Hey all, I need a jQuery action to fire when a user scrolls past certain locations on the page. Is this even possible with jQuery? I have looked at .scroll in the jQuery API and I don't think this is what I need. It fires every time the user scrolls, but I need it to fire just when a user passes a certain area.
Use the jquery event .scroll()
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
http://jsfiddle.net/babumxx/hpXL4/
Waypoints in jQuery should do it:
http://imakewebthings.github.com/jquery-waypoints/
$('#my-el').waypoint(function(direction) {
console.log('Reached ' + this.element.id + ' from ' + direction + ' direction.');
});
jQuery waypoints plugin documentation: http://imakewebthings.com/waypoints/guides/jquery-zepto/
To fire any action only once on a single page I have modified jondavid's snippet as following.
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
//do your stuff over here
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
Scroll down to Run code snippet
Here you can check example of working code snippet;
jQuery(document).ready(function($){
$triggered_times = 0;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = 150; // set to whatever you want it to be
if(y_scroll_pos > scroll_pos_test && $triggered_times == 0 ) {
alert('This alert is triggered after you have scroll down to 150px')
$triggered_times = 1; // to make sure the above action triggers only once
}
});
})
p {
height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<p>scroll down this block to get an alert</p>
</body>

Categories

Resources