jQuery uncaught TypeError: Infinite scroll - javascript

So, I am following the tutorial to implement infinite scroll: http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/comment-page-3/
In my footer, I added <script type="text/javascript" src="http://example.com/js/jquery.infinitescroll.min.js"></script>
In the javascript.js file, I added the following (identical to the tutorial):
// infinitescroll() is called on the element that surrounds
// the items you will be loading more of
$('#content').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a:first",
// selector for the NEXT link (to page 2)
itemSelector : "#content div.post"
// selector for all items you'll retrieve
});
However, I am getting Uncaught TypeError: jQuery(...).infinitescroll is not a function error.
So, I added the js file and added the script pretty much identical to the tutorial. I can see that both js file and scripts are shown on the page, but still getting the error.
Could someone help me why I am getting an error?
Thanks!

You should make sure your initialization code is inside a $(function(){}), because you need the DOM to be ready before running infinitescroll. Then you have to make sure there is an element with id="content" in your page. So, make sure you have something like this:
<div id="content">...</div>
<script src="jquery.infinitescroll.js"></script>
<script>
$(function() {
// infinitescroll() is called on the element that surrounds
// the items you will be loading more of
$('#content').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a:first",
// selector for the NEXT link (to page 2)
itemSelector : "#content div.post"
// selector for all items you'll retrieve
});
});
</script>

Did you add the plugin file in the page header?
You have to download it from the plugin page you have provided and add it as:
<script src="jquery.infinitescroll.js"></script>
in the head section of the page after the script tag where you load jQuery
Please adapt the src to the path to the directory you have placed the js into.

If you use webpack then use this code
var InfiniteScroll = require('infinite-scroll');
var infScroll = new InfiniteScroll('.container', {
// options
path: ".pagination__next",
append: ".post",
history: false
});

Related

Getting Uncaught TypeError: undefined is not a function in nivo slider.js

I am trying to put nivo-slider on my drupal home page. Although all images are showing but they are not sliding and when I check consol, I see an error in nivo-slider.js file i.e.
"Uncaught TypeError: undefined is not a function"
My nivo-slider.js code is-
(function ($) {
Drupal.behaviors.nivoSlider = {
attach: function (context, settings) {
// Initialize the slider
$('#slider').nivoSlider({ *//here I am getting error mentioned above*
'effect': Drupal.settings.nivo_slider.effect, // Specify sets like: 'fold,fade,sliceDown'
'slices': Drupal.settings.nivo_slider.slices, // For slice animations
'boxCols': Drupal.settings.nivo_slider.boxCols, // For box animations
'boxRows': Drupal.settings.nivo_slider.boxRows, // For box animations
'animSpeed': Drupal.settings.nivo_slider.animSpeed, // Slide transition speed
'pauseTime': Drupal.settings.nivo_slider.pauseTime, // How long each slide will show
'startSlide': Drupal.settings.nivo_slider.startSlide, // Set starting Slide (0 index)
'directionNav': Drupal.settings.nivo_slider.directionNav, // Next & Prev navigation
'directionNavHide': Drupal.settings.nivo_slider.directionNavHide, // Only show on hover
'controlNav': Drupal.settings.nivo_slider.controlNav, // 1,2,3... navigation
'controlNavThumbs': Drupal.settings.nivo_slider.controlNavThumbs, // Use thumbnails for Control Nav
'pauseOnHover': Drupal.settings.nivo_slider.pauseOnHover, // Stop animation while hovering
'manualAdvance': Drupal.settings.nivo_slider.manualAdvance, // Force manual transitions
'prevText': Drupal.settings.nivo_slider.prevText, // Prev directionNav text
'nextText': Drupal.settings.nivo_slider.nextText, // Next directionNav text
'randomStart': Drupal.settings.nivo_slider.randomStart, // Start on a random slide
'beforeChange': Drupal.settings.nivo_slider.beforeChange, // Triggers before a slide transition
'afterChange': Drupal.settings.nivo_slider.afterChange, // Triggers after a slide transition
'slideshowEnd': Drupal.settings.nivo_slider.slideshowEnd, // Triggers after all slides have been shown
'lastSlide': Drupal.settings.nivo_slider.lastSlide, // Triggers when last slide is shown
'afterLoad': Drupal.settings.nivo_slider.afterLoad // Triggers when slider has loaded
});
}
};
}(jQuery));
Help me to sought out this error..thanks!!
Include jquery.js main file in header before any js
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
When you use two different versions of jquery (which is not recommended), you can use
jQuery.noConflict
api.jquery.com/jQuery.noConflict/
I had encountered a similar problem before. This issue can be fixed by making use of Jquery Update module in Drupal 7 & setting the version of jquery library to 1.9 & above.
Do let me know in case of any doubts
Also please note that in Drupal you should never add Jquery library explicitly because Drupal core by default adds a jquery library.
When you try to add a jquery.js in the head
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
There will be 2 jquery libraries now & which will conflict.
So we need to use jquery update module to upgrade the library
Another likely candidate is referring to jQuery with $ (dollar):
$(document).ready(function(){
// Target your .container, .wrapper, .post, etc.
$("#main-content").fitVids();
});
If you instead use the no-conflict reference in your script, as below, this may fix the error
jQuery(document).ready(function(){
// Target your .container, .wrapper, .post, etc.
jQuery("#main-content").fitVids();
});
I just ran into some issues configuring Nivo View Slider on Drupal 7.
I didn't read the module's documentation at first but it looks like Nivo Slider's library isn't included in the package, you need to upload it manually to your server.
Here is the documentation : https://www.drupal.org/project/views_nivo_slider
To sum it up :
install/enable Library API
download Nivo Slider libs from https://github.com/gilbitron/Nivo-Slider/downloads
unzip the archive to sites/all/libraries/nivo-slider
At step 2, you'll have to choose between version 2.x or 3.x
On the module's project page, it says that version 3.x might be broken on Google Chrome, I didn't have any issue myself...

Load External Panel To Jquery Mobile Page

JQuery Mobile template which utilises a side panel. For simplicity I want to be able to load this panel from an 'external page' / seperate document so that it can be built once and used on many pages.
A bit of research has resulted in me getting the following code to load a string of html into a variable and then loading that variable into each page as the side panel:
/* Get the sidebar-panel as a var */
var side_var = '<div data-role="panel" id="left-panel" data-position="left" data-display="push"><h1>Panel</h1><p>stuff</p></div>';
/* Load the side-panel var to the DOM / page */
$(document).one('pagebeforecreate', function () {
$.mobile.pageContainer.prepend( side_var );
$("#left-panel").panel();
});
This works perfectly, however it still doesn't address the need to build the sidebar / panel as a separate html file.
A bit more work and I discovered this snippet to load a page into a variable:
$.get("http://www.somepage.com", function( side_var ) {}, 'html');
So in theory adding the two together should give me the desired result;
/* Get the sidebar-panel as a var */
$.get("mypage.html", function( side_var ) {}, 'html');
/* Load the side-panel var to the DOM / page */
$(document).one('pagebeforecreate', function () {
$.mobile.pageContainer.prepend( side_var );
$("#left-panel").panel();
});
However, all I get when running this is an eternally rotating AJAX loader.
What am I missing &/or doing wrong??
COMPLETE SOLUTION
Omar's solution below goes most of the way but needs one small but important addition to make the JQM elements display as expected. Here is the complete solution:
$(document).one("pagebeforecreate", function () {
$.get('side-panel.html', function(data) {
//$(data).prependTo($.mobile.pageContainer); //or .prependTo("body");
$.mobile.pageContainer.prepend(data);
$("[data-role=panel]").panel().enhanceWithin(); // initialize panel
}, "html");
});
Each element to be enhanced as a JQM element needs the data-theme adding to tell it which theme to use. Additionally in the JavaScript the initialised panel widget needs to .enhanceWithin() in order for the elements to be rendered with the desired style.
the $.get() function should be wrapped in pagebeforecreate event, to append contents directly once retrieved. Also, you need to initialize retrieved contents.
$(document).one("pagebeforecreate", function () {
$.get('mypage.html', function(data){
$(data).prependTo("body"); // or .prependTo($.mobile.pageContainer);
$("[data-role=panel]").panel(); // initialize panel
}, "html");
});

Moving inline js into external js file causing errors

I was trying to tidy up the inline js scripts for a template I'm modifying and combining them into an external js file when I noticed some errors in the console. They are not doing any harm to the site's functionality but I am wondering what I'm doing wrong and how to fix it.
My external js file is:
<script type="text/javascript" src="web/js/init.js"></script>
Link 1 throws the following error:
Uncaught TypeError: Object [object Object] has no method 'owlCarousel'
(I don't use that carousal on that page...)
Link 2 where I do use the carousal throws this error:
Uncaught TypeError: Object [object Object] has no method 'nivoSlider'
(I don't use the slider on that page)
Link 3 I left the inline scripts (no external js file) in place and no js errors relating to external/internal js.
Thanks!
You are calling nivoslider() and not using its js file that why you are getting error for nivoslider, remove the below lines from your init.js From your puppies page
$(window).load(function() {
$('#slider').nivoSlider();
});
Same problem with you owlcarousel remove the below code from init.js for your index page
$("#owl-example").owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 3,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
If your id slider and owl-example used for nivoslider and owlCarousel only then you can do it by checking length of your elements like,
$(function() {
if($('#slider') && $('#slider').length){// must be on puppies page only
$('#slider').nivoSlider();
}
if($('#owl-example') && $('#owl-example').length){// must be on index page only
$("#owl-example").owlCarousel({
autoPlay: 3000, //Set AutoPlay to 3 seconds
items : 3,
itemsDesktop : [1199,3],
itemsDesktopSmall : [979,3]
});
}
});
1) You are targeting an element that does not exist on the page. There is no element with an ID of owl-example, so jquery returns nothing and a method is being called on this null value. ( See here on SO how to test for null first )
2) Same as above but with an element with the ID of slider. It doesn't exist on this page, so a method is being called on null.
Your code looks like
$(function(){
//Code..
})
These functions are all being called when the DOM loads. See this SO question.
3) You are not getting errors on this page because the jquery selectors you are using are returning elements in the page that match. This doesn't have anything to do with inline/external.

Cant make Tinymce edit iframe to work with tabbifier

Im trying to get tinymce edit iframe to work with this wonderfull tabbifier:
http://www.barelyfitz.com/projects/tabber
I have successfully installed both of them and they work great.
In my example I have tested the following:
Load a tinymce component and save the following code inside the tinymce iframe with the HTML option:
test
The result is saved perfectly after refreshing with F5 and this code is saved in the database:
<p>test</p>
tinymce is working perfecly.
The next test I have made is with tabber:
Edit the tinymce component box and saved the following code with the HTML option:
<div class='tabber' id='tabber1'>
<div class='tabbertab' title='FIRSTTAB' >
test firsttab
</div>
<div class='tabbertab' title='SECONDTAB' >
test secondtab
</div>
</div>
The code is perfectly saved in the database, and the result is perfectly loaded in the output view, showing two tabs, each one of them with its content.
The problem is while trying to edit the content again with tinymce, the tabs are not shown. The content is perfectly loaded in the tinymce iframe, without the tabs. Its shown as below:
test firsttab
test secondtab
The HTML code inside it is good, it has the proper tabbifier html code saved before.
The problem maybe is that the iframe of tinymce is not able to load or interpret the javascript of tabber.js and its not showing the tabs.
I have tested loading the javascript of tabber.js inside the tinymce iframe with this code, and seems to load it but the tabs are not still shown:
<script type="text/javascript">
tinyMCE.init({
mode: "exact",
elements: "%s",
theme: "%s",
%s
%s
theme_advanced_toolbar_location: "top",
theme_advanced_toolbar_align: "left",
theme_advanced_statusbar_location: "bottom",
theme_advanced_resizing: true
%s
setup : function(ed)
{
ed.onInit.add(function(ed, evt)
{
alert("entered tiny");
// Load a script from a specific URL using the global script loader
//tinymce.ScriptLoader.load('/js/tabber/tabber.js');
// Load a script using a unique instance of the script loader
//var scriptLoader = new tinymce.dom.ScriptLoader();
//scriptLoader.load('C:\tabber.js');
// Load multiple scripts
var scriptLoader = new tinymce.dom.ScriptLoader();
scriptLoader.add('/js/tabber.js');
scriptLoader.loadQueue(function() { alert('All scripts are now loaded.'); });
});
}
});
</script>
I have also checked that /js/tabber.js is the correct path. And saw at firebug that its loading it.
The two alert messages are displayed, so it seems to load it, but the tabs inside the tinymce edit iframe are still not shown.
Any help is welcome, thank you so much.
The tinymce ScriptLoader does not load a script inside the iframe. It provide a way to load a script in the main window after the tinymce initialization. This is very confusing as not documented.
But you definitelty can load a script inside the iframe. Here is the magic :
tinymce.init( { setup : function( ed ) {
ed.on('init', function (args) {
// get the iframe DOM
var doc = args.target.contentDocument || args.target.contentWindow.document;
// inject script into the DOM
var s = doc.createElement('script');
s.type = 'text/javascript';
s.src = '/js/tabber.js';
doc.getElementsByTagName('head')[0].appendChild(s);
});
});
Several browsers have problems with spaces and tabs on paragraph start.
A workaround for spaces is to code them onSave as protected spaces if they are at the beginning. The solution for tabs is to use another character with similar behaviour and replace them when saving. It is necessary to recode the content when reloaded from databse into the editor.

Infinite scrollbar in Javascript

I am writing a book viewer that dynamically loads content as the user scrolls down to it. The first problem I'm having is how to set up the scrollbar. Since we only store paragraphs in our database with no size information, I can only guess how long the document is. Based upon such a guess, I may want to create a scrollable window that appears 10,000 pixels long and loads paragraphs as needed.
The simplest way I can think is to actually create a DIV that is 10,000 pixels long and absolutely position an embedded div at the scroll position showing my content.
Is there a way to totally control the scrollbar under Javascript (setting its min, max, position, relative thumb size) or do I go the simple way mentioned above or is there another way to do this?
I am using ExtJS framework but it does not seem to offer any direct help there, though V4 does include an infinite grid.
The other answers to this question simply extended the content as the user reached the bottom, this is not what I was after. I need to display a fully sized, but sparsely populated, scrollable region. The solution I came up with was pretty simple:
I created a scrollable DIV (call it book) with a set of inner DIVs for each paragraph in the book. I need to do it by paragraph as this has special meaning in our application, otherwise, you'd probably do it by page. The paragraph DIVs have a default size based upon a guess of how big they are.
When the book DIV is scrolled, the javascript calculates which paragraph DIVs are now visible. Those that are visible but are not populated are bundled together. A web service is then used to populate the required paragraph DIVs and accurately size them.
The algorithm I use bundles some surrounding (not not-visible) paragraphs to give some read ahead and chunking efficiencies. A lazy loader reads further paragraphs once the screen has been updated to further aid smooth scrolling.
This turned out too be very simple. The hard work is in the chunking algorithms and adding a lazy reader.
Here is a number of ways:
Masonry Infinite Scroll http://desandro.com/demo/masonry/docs/infinite-scroll.html
Cpde Sample:
$wall.infinitescroll({
navSelector : '#page_nav', // selector for the paged navigation
nextSelector : '#page_nav a', // selector for the NEXT link (to page 2)
itemSelector : '.box', // selector for all items you'll retrieve
loadingImg : 'img/loader.gif',
donetext : 'No more pages to load.',
debug: false,
errorCallback: function() {
// fade out the error message after 2 seconds
$('#infscr-loading').animate({opacity: .8},2000).fadeOut('normal');
}
},
// call masonry as a callback
function( newElements ) {
$(this).masonry({ appendedContent: $( newElements ) });
}
);
AJAXian Way (No Plugin) http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery
Code:
//Scroll Detection
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
//Loading More content
function lastPostFunc()
{
$(’div#lastPostsLoader’).html(’<img src="bigLoader.gif"/>’);
$.post("scroll.asp?action=getLastPosts&lastID=" + $(".wrdLatest:last").attr("id"),
function(data){
if (data != "") {
$(".wrdLatest:last").after(data);
}
$(’div#lastPostsLoader’).empty();
});
};
Infinite Scroll jQuery Plugin (Originally WordPress Plugin) http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
Sample Code:
// infinitescroll() is called on the element that surrounds
// the items you will be loading more of
$('#content').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a:first",
// selector for the NEXT link (to page 2)
itemSelector : "#content div.post"
// selector for all items you'll retrieve
});
All options
// usage:
// $(elem).infinitescroll(options,[callback]);
// infinitescroll() is called on the element that surrounds
// the items you will be loading more of
$('#content').infinitescroll({
navSelector : "div.navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : "div.navigation a:first",
// selector for the NEXT link (to page 2)
itemSelector : "#content div.post",
// selector for all items you'll retrieve
debug : true,
// enable debug messaging ( to console.log )
loadingImg : "/img/loading.gif",
// loading image.
// default: "http://www.infinite-scroll.com/loading.gif"
loadingText : "Loading new posts...",
// text accompanying loading image
// default: "<em>Loading the next set of posts...</em>"
animate : true,
// boolean, if the page will do an animated scroll when new content loads
// default: false
extraScrollPx: 50,
// number of additonal pixels that the page will scroll
// (in addition to the height of the loading div)
// animate must be true for this to matter
// default: 150
donetext : "I think we've hit the end, Jim" ,
// text displayed when all items have been retrieved
// default: "<em>Congratulations, you've reached the end of the internet.</em>"
bufferPx : 40,
// increase this number if you want infscroll to fire quicker
// (a high number means a user will not see the loading message)
// new in 1.2
// default: 40
errorCallback: function(){},
// called when a requested page 404's or when there is no more content
// new in 1.2
localMode : true
// enable an overflow:auto box to have the same functionality
// demo: http://paulirish.com/demo/infscr
// instead of watching the entire window scrolling the element this plugin
// was called on will be watched
// new in 1.2
// default: false
},function(arrayOfNewElems){
// optional callback when new content is successfully loaded in.
// keyword `this` will refer to the new DOM content that was just added.
// as of 1.5, `this` matches the element you called the plugin on (e.g. #content)
// all the new elements that were found are passed in as an array
});
// load all post divs from page 2 into an off-DOM div
$('<div/>').load('/page/2/ #content div.post',function(){
$(this).appendTo('#content'); // once they're loaded, append them to our content area
});
Load Content While Scrolling With jQuery (Another No PLugin Sample) http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/
Code:
function lastPostFunc()
{
$('div#lastPostsLoader').html('<img src="bigLoader.gif">');
$.post("scroll.asp?action=getLastPosts&lastID=" + $(".wrdLatest:last").attr("id"),
function(data){
if (data != "") {
$(".wrdLatest:last").after(data);
}
$('div#lastPostsLoader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
lastPostFunc();
}
});
Try this infinite scroller I found on Smashing Magazine this morning:
http://markholton.com/posts/17-infiniscroll-jquery-plugin-released

Categories

Resources