Overlay Scrollbars - Can't get the destroy() method working - javascript

I'm using OverlayScrollbars on my website (https://github.com/KingSora/OverlayScrollbars) to display a custom scroll bar in each of my sections.
For design reasons, I want to use this custom scroll bar only for screens above width 1200 px.
I read in the documentation about the destroy() method that would do exactly what I want to achieve : clean the Dom of any style from the custom scroll bar (for me, when screen is getting smaller than 1200 px wide).
When I use the destroy() method, my console returns me the following error:
Uncaught TypeError: instance.destroy is not a function
I'm quite new with JavaScript, so I tried different syntaxes, but always ended up with the same error.
$(document).ready(function() {
var $window = $(window);
function checkWidth() {
var windowsize = $window.width();
if (windowsize >= 1200) {
//if the window is bigger 1200px wide then turn on ScrollBar..
$(function() {
var instance = OverlayScrollbars(document.querySelectorAll("section"), { });
});
}
else if (windowsize < 1200) {
//if the window is smaller than 440px wide then destroy ScrollBar..
$(function() {
var instance = OverlayScrollbars(document.querySelectorAll("section"), { });
instance.destroy();
});
}
}
checkWidth();
$(window).resize(checkWidth);
});

try to use
var instance =$ ( '.section' ).overlayScrollbars ( { ... } ).overlayScrollbars()
instance.destroy()

Related

sidebar fixed only on screen size > 992px and above still not working properly

I want to create a sidebar whose position is fixed only when the screen size is 992px and above. I've made the sidebar position fixed, but when the screen is 991 down the position is still fixed. I want when the screen size is 991px and down the position is relative.
but when i refresh the page, it works normally. Is there a strange behavior with the use of this javascript code?
Anyone can help me to solved this problem?
if ($(window).width() >= 992) {
var theLoc = 150;
var links = $('.d-submenu');
var content = $('.main-content');
$(window).scroll(function () {
console.log('scroll');
if (theLoc >= $(window).scrollTop()) {
if (links.hasClass('fixed')) {
links.removeClass('fixed');
content.removeClass('fixed');
}
} else {
if (!links.hasClass('fixed')) {
links.addClass('fixed');
content.addClass('fixed');
}
}
});
}
You need to add a event listener for page resize something like
$(window).on('resize', function(){
var win = $(this); //this = window
if (win.width() >= 992) { /* ... */ }
});
EDIT FOR FULL SOLUTION
function screenResize() {
if ($(window).width() >= 992) {
var theLoc = 150;
var links = $('.d-submenu');
var content = $('.main-content');
} REST OF YOUR CODE
// On page load call
screenResize();
// And recheck when window gets resized.
$(window).on('resize',function(){
screenResize();
});

What is a good way to make an event occur when the page has loaded OR on each resize?

I need a query to check the viewport width each time the document is ready or whenever the viewport gets resized. The reason is that I want the main navigation to look and behave differently for different viewport widths.
//EventListener to get viewport width on load
window.addEventListener("load", function () {
window.loaded = true;
});
//get Window Size on Resize
var width = $(window).width();
$(window).on('resize', function reportWindowSize() {
if ($(this).width() != width) {
width = $(this).width();
console.log(width);
}
});
Then I think I need a query like this:
If (page loaded OR viewport width changes) {
if (viewport width > x) {
do things
} else if (viewport width < x) {
do other things
}
};
What would be a good way to form If (page loaded OR viewport width changes) into a JavaScript or jQuery expression?
As Terry pointed out in his comment, you can create a function and reuse it in each of the scenarios that you need it.
I.E.
function checkWidth() {
let windowWidth = $(window).width();
let maxWidth = 1000;
if(windowWidth < maxWidth) {
// do your stuff
}
}
$(document).ready(function() {
checkWidth();
});
$(window).on('resize', function() {
checkWidth();
});
Another solution would be to use Media Queries inside JS.
You can watch for a media query as you would in CSS with the following code:
if (matchMedia) {
let mq = window.matchMedia("(min-width: 500px)");
mq.addListener(checkWidth);
checkWidth(mq);
}
// media query change
function checkWidth(mq) {
if (mq.matches) {
// do your stuff
}
}
You need to call checkWidth after adding the event listener in order to ensure that it executes when the page is loaded.
I got this example from: https://www.sitepoint.com/javascript-media-queries/

From vertical to horizontal slider

I have this slider on my WP page, which is vertical. I would like to convert it so it his horizontal. As I understood I need to change my JS code.
jQuery(function($) {
var image_es;
var zoom_timer;
var win_width = 0;
function resize_venedor_thumbs() {
if (win_width != $(window).width()) {
if (image_es) {
image_es.destroy();
}
image_es = $('#thumbnails-slider-756').elastislide({
orientation : 'vertical',
minItems: 4
});
win_width = $(window).width();
}
if (zoom_timer) clearTimeout(zoom_timer);
}
$(window).load(resize_venedor_thumbs);
$(window).resize(function() {
clearTimeout(zoom_timer);
zoom_timer = setTimeout(resize_venedor_thumbs, 400);
});
});
I tried to change vertical to horizontal in inspect element mode but it did not change at all.
If you change the orientation to 'horizontal' in inspect element mode, you need to make sure the resize_venedor_thumbs function is called.
It looks like it is called on load or resize (try resize because loading will erase your edits); or you can call it in the console yourself resize_venedor_thumbs(); or, of course, edit the source and load the page.

jQuery function on window events (load and resize)

I'm not sure how to use the order of the window events load and resize on jQuery to make it work when resizing. The first function is used to get the total width except the scrollbar width, because the CSS is using the device width, but the JS is using the document width.
The second function adds a style when the total screen width is between 768px and 1024px, and it should work when I load the page at any screen, after resizing, etc. I'm doing a lot of tests and I think the problem is about the window events order.
For being more specific about the problems, it doesn't remove the style when I load the page at 900px and I expand it to > 1024px! Or by the contrary, it doesn't add the style when I load the page at 1300px and I shorten the width to 900px.
I think it's 'cause of the load and resize events order, but I'm not totally sure. Or maybe I'm not doing the correct declaration of the variable into the resize.
The code:
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
$(document).ready(function(){
var vpwidth=$(window).width();
$(window).on('resize', function(){
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
I believe the issue is that you're not re-calculating the vpwidth on resize, So the value you got when the page was loaded will be used every time window is resized.
try
$(document).ready(function(){
$(window).on('resize', function(){
var vpwidth=$(window).width(); // get the new value after resize
var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;
if(vpwidth >= 768 && vpwidth <= 1024) {
$('.contentleft, .contentright').css('width', changeWidth + 'px');
} else {
$('.contentleft, .contentright').removeAttr('style');
}
}).resize();
});
The issue is because you are not recalculating the width (vpwidth) on resize function.
It is initialized and set on page load itself and hence doesn't change when the window is resized causing the style to not be added or removed.
You need to re-assign the value to the variable from within the resize function.
$(window).on('resize', function(){
var vpwidth=$(window).width();
}
Demo Fiddle

infinite-scroll jquery plugin

I am trying to set up infinite-scroll on a site I am developing with Coldfusion, I am new to javascript and jquery so I am having some issues wrapping my head around all of this. Do I need to have pagination on my site in order to use the infinite-scroll plugin, or is there a way to do it with out it?
You do not need infinite scroll plug-in for this. To detect when scroll reaches end of page, with jQuery you can do
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
//Add something at the end of the page
}
});
Demo on JsFiddle
I'm using Hussein's answer with AJAX requests. I modified the code to trigger at 300px instead of 10px, but it started causing my appends to multiply before the AJAX request was finished since the scroll call triggers much more frequently in a 300px range than a 10px range.
To fix this, I added a trigger that would be flipped on successful AJAX load. My code looks more like this:
var scrollLoad = true;
$(window).scroll(function () {
if (scrollLoad && $(window).scrollTop() >= $(document).height() - $(window).height() - 300) {
scrollLoad = false;
//Add something at the end of the page
}
});
then in my AJAX response, I set scrollLoad to true.
I built on top of Hussein's little example here to make a jQuery widget. It supports localStorage to temporarily save appended results and it has pause functionality to stop the appending every so often, requiring a click to continue.
Give it a try:
http://www.hawkee.com/snippet/9445/
$(function(){
$(window).scroll(function(){
if($(document).height()<=$(window).scrollTop()+$(window).height()+100){
alert('end of page');
}
});
});
Some one asked for explanation so here is the explanation
here $(document).height()-->is the height of the entire document.In most cases, this is equal to the element of the current document.
$(window).height()-->is the height of the window (browser) means height of whatever you are seeing on browser.
$(window).scrollTop()-->The Element.scrollTop property gets or sets the number of pixels that the content of an element is scrolled upward. An element's scrollTop is a measurement of the distance of an element's top to its topmost visible content. When an element content does not generate a vertical scrollbar, then its scrollTop value defaults to 0.
$(document).height()<=$(window).scrollTop()+$(window).height()+100
add $(window).scrollTop() with $(window).height() now check whether the result is equal to your documnet height or not. if it is equal means you reached at the end.we are adding 100 too because i want to check before the 100 pixels from the bottom of document(note <= in condition)
please correct me if i am wrong
I had same problem but didn't find suitable plugin for my need. so I wrote following code. this code appends template to element by getting data with ajax and pagination.
for detecting when user scrolls to bottom of div I used this condition:
var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();
if (dh - (wh + ws) < dh - (h + t)) {
//now you are at bottom of #infiniteContent element
}
$(document).ready(function(){
$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: 1, _limit:3 }, function (jsonre) {
appendTemplate(jsonre,1);
});
});
function appendTemplate(jsonre, pageNumber){
//instead of this code you can use a templating plugin like "Mustache"
for(var i =0; i<jsonre.length; i++){
$("#infiniteContent").append("<div class='item'><h2>"+jsonre[i].name+"</h2><p>"+jsonre[i].body+"</p></div>");
}
if (jsonre.length) {
$("#infiniteContent").attr("data-page", parseInt(pageNumber)+1);
$(window).on("scroll", initScroll);
//scroll event will not trigger if window size is greater than or equal to document size
var dh = $(document).height() , wh = $(window).height();
if(wh>=dh){
initScroll();
}
}
else {
$("#infiniteContent").attr("data-page", "");
}
}
function initScroll() {
var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();
if (dh - (wh + ws) < dh - (h + t)) {
$(window).off('scroll');
var p = $("#infiniteContent").attr("data-page");
if (p) {
$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: p, _limit:3 }, function (jsonre) {
appendTemplate(jsonre, p);
});
}
}
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="infiniteContent"></div>
If you have a scrollable element, like a div with scroll overflow, but no scrollable document/page, you can take this way.
$(function () {
var s = $(".your-scrollable-element");
var list = $("#your-table-list");
/* On element scroll */
s.scroll(function () {
/* The scroll top plus element height equals to table height */
if ((s.scrollTop() + s.height()) == list.height()) {
/* you code */
}
});
});
I wrote this function using Hussein and Nick's ideas, but I wanted it to use promises for the callback. I also wanted the infinite scrolling area to be on a fixed div and not just the window if the div is sent into the options object. There is an example of that in my second link below. I suggest using a promise library like Q if you want to support older browsers. The cb method may or may not be a promise and it will work regardless.
It is used like so:
html
<div id="feed"></div>
js
var infScroll = infiniteScroll({
cb: function () {
return doSomethingPossiblyAnAJAXPromise();
}
});
If you want the feed to temporarily stop you can return false in the cb method. Useful if you have hit the end of the feed. It can be be started again by calling the infiniteScroll's returned object method 'setShouldLoad' and passing in true and example to go along with the above code.
infScroll.setShouldLoad(true);
The function for infinite scrolling is this
function infiniteScroll (options) {
// these options can be overwritten by the sent in options
var defaultOptions = {
binder: $(window), // parent scrollable element
loadSpot: 300, //
feedContainer: $("#feed"), // container
cb: function () { },
}
options = $.extend(defaultOptions, options);
options.shouldLoad = true;
var returnedOptions = {
setShouldLoad: function (bool) { options.shouldLoad = bool; if(bool) { scrollHandler(); } },
};
function scrollHandler () {
var scrollTop = options.binder.scrollTop();
var height = options.binder[0].innerHeight || options.binder.height();
if (options.shouldLoad && scrollTop >= (options.binder[0].scrollHeight || $(document).height()) - height - options.loadSpot) {
options.shouldLoad = false;
if(typeof options.cb === "function") {
new Promise(function (resolve) {resolve();}).then(function() { return options.cb(); }).then(function (isNotFinished) {
if(typeof isNotFinished === "boolean") {
options.shouldLoad = isNotFinished;
}
});
}
}
}
options.binder.scroll(scrollHandler);
scrollHandler();
return returnedOptions;
}
1 feed example with window as scroller
2 feed example with feed as scroller

Categories

Resources