Complex jquery scroll - javascript

I need to trigger a function specifically after an user scroll almost at the bottom of the page then up until certain point. How do I do it properly?
advertisement.refreshAd = function() {
$(window).scroll(function(event) {
if('almost at the end then scroll up to certain point')
{console.log('trigger refresh!');}
});
}

What you are looking for is the jQuery function scrollTop(). The code would look something like this:
var atEnd = false;
advertisement.refreshAd = function() {
$(window).scroll(function(event) {
if($(document).scrollTop() > $(document).height()-500) { //point1
atEnd = true;
} if (($(document).scrollTop() < point2) && atEnd){
console.log('trigger refresh!');
}
});
}

Try below code
<script>
var touchedBottom = 0;
jQuery(window).scroll(function(event) {
if(jQuery(window).scrollTop() + jQuery(window).height() == jQuery(document).height()) {
touchedBottom = 1;
console.log("touched Bottom");
}
if(touchedBottom){
if(jQuery(window).scrollTop() < jQuery("#point_2").offset().top){
touchedBottom = 0;
console.log("touched point 1");
}
}
});
</script>

advertisements.refreshAd = function() {
var furthestPoint = false;
var point2 = 1700 //will be dynamic;
var lastScrollTop = 0;
var scrolledToPosition = false;
$(window).scroll(function() {
var st = $(this).scrollTop();
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
furthestPoint = true;
}
if (st < lastScrollTop && st < point2 && furthestPoint){
if (!scrolledToPosition) {
console.log('TRIGGER! - once only!');
scrolledToPosition = true;
}
}
lastScrollTop = st;
});
};
advertisements.refreshAd();

Related

How to remove or add class in nav when the browser window goes down or up

I have nav with four elements. I try add class (eg. with underline in css) in this element witch user is on. But when user scroll up or down I want remove that class and add in diffrent element in nav depending on where the user stayed.
Here is my code:
let currentPosition = window.scrollY;
let basicFunctionPosition = document.querySelector("#basic-function").offsetTop;
let moreFunctionsPosition = document.querySelector("#more-functions").offsetTop;
let signUpPosition = document.querySelector("#sign-up").offsetTop;
let teamPosition = document.querySelector('#team').offsetTop;
let dataSectionInNav = "";
let dataSectionInNavTeam = "";
if (currentPosition > basicFunctionPosition && currentPosition < moreFunctionsPosition) {
dataSectionInNav = document.querySelector(".data-section-basic-func");
dataSectionInNav.classList.add("sectionPositionInNav");
} else if (currentPosition > moreFunctionsPosition && currentPosition < signUpPosition) {
dataSectionInNav = document.querySelector(".data-section-more-func");
dataSectionInNav.classList.add("sectionPositionInNav");
} else if (currentPosition > signUpPosition && currentPosition < teamPosition) {
dataSectionInNav = document.querySelector(".data-section-sign-up");
dataSectionInNav.classList.add("sectionPositionInNav");
dataSectionInNavTeam = document.querySelector(".data-section-team");
dataSectionInNavTeam.classList.add("sectionPositionInNav");
}
});
You need to loop over your conditionals when the user scrolls:
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
let last_known_scroll_position = 0;
let ticking = false;
function doSomething(scroll_pos) {
// Do something with the scroll position
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});
The example above uses requestAnimationFrame to ease the rate at which your function runs.
Check the Docs for more information.
Afterwards I use this code,
document.addEventListener("scroll", function () {
let currentPosition = window.scrollY;
let basicFunctionPosition = document.querySelector("#basic-function").offsetTop;
let moreFunctionsPosition = document.querySelector("#more-functions").offsetTop;
let signUpPosition = document.querySelector("#sign-up").offsetTop;
let teamPosition = document.querySelector("#team").offsetTop;
let addClass = "";
let delateClass = "";
if (currentPosition < basicFunctionPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-more-func, .data-section-sign-up, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
} else if (currentPosition > basicFunctionPosition && currentPosition < moreFunctionsPosition) {
delateClass = document.querySelectorAll(".data-section-more-func, .data-section-sign-up, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-basic-func");
addClass.classList.add("highlightNav");
} else if (currentPosition > moreFunctionsPosition && currentPosition < signUpPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-sign-up, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-more-func");
addClass.classList.add("highlightNav");
} else if (currentPosition > signUpPosition && currentPosition < teamPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-more-func, .data-section-team");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-sign-up");
addClass.classList.add("highlightNav");
} else if (currentPosition > teamPosition) {
delateClass = document.querySelectorAll(".data-section-basic-func, .data-section-more-func, .data-section-sign-up");
delateClass.forEach((item) => {
item.classList.remove("highlightNav");
});
addClass = document.querySelector(".data-section-team");
addClass.classList.add("highlightNav");
}
});
Can you write the code more simply?

Parallax scroll not working on mobile

Hi there I have a parallax effect scroll on my website, it is all working good on desktop but mobile device it is not working properly when I attempt to even scroll/swipe down the page.
Here is the javascript:
var ticking = false;
var isFirefox = /Firefox/i.test(navigator.userAgent);
var isIe = /MSIE/i.test(navigator.userAgent) || /Trident.*rv\:11\./i.test(navigator.userAgent);
var scrollSensitivitySetting = 30;
var slideDurationSetting = 800;
var currentSlideNumber = 0;
var totalSlideNumber = $('.background').length;
function parallaxScroll(evt) {
if (isFirefox) {
delta = evt.detail * -120;
} else if (isIe) {
delta = -evt.deltaY;
} else {
delta = evt.wheelDelta;
}
if (ticking != true) {
if (delta <= -scrollSensitivitySetting) {
ticking = true;
if (currentSlideNumber !== totalSlideNumber - 1) {
currentSlideNumber++;
nextItem();
}
slideDurationTimeout(slideDurationSetting);
}
if (delta >= scrollSensitivitySetting) {
ticking = true;
if (currentSlideNumber !== 0) {
currentSlideNumber--;
}
previousItem();
slideDurationTimeout(slideDurationSetting);
}
}
}
function slideDurationTimeout(slideDuration) {
setTimeout(function () {
ticking = false;
}, slideDuration);
}
var mousewheelEvent = isFirefox ? 'DOMMouseScroll' : 'wheel';
window.addEventListener(mousewheelEvent, _.throttle(parallaxScroll, 60), false);
function nextItem() {
var $previousSlide = $('.background').eq(currentSlideNumber - 1);
$previousSlide.css('transform', 'translate3d(0,-130vh,0)').find('.content-wrapper1').css('transform', 'translateY(40vh)');
currentSlideTransition();
}
function previousItem() {
var $previousSlide = $('.background').eq(currentSlideNumber + 1);
$previousSlide.css('transform', 'translate3d(0,30vh,0)').find('.content-wrapper1').css('transform', 'translateY(30vh)');
currentSlideTransition();
}
function currentSlideTransition() {
var $currentSlide = $('.background').eq(currentSlideNumber);
$currentSlide.css('transform', 'translate3d(0,-15vh,0)').find('.content-wrapper1').css('transform', 'translateY(15vh)');
;
}
Your help would be appreciated thank you!

How to make anchor tag work for scrolling

I am trying to implement this code on my site:
Since it is a WordPress site made with page builder, I had to add all the anchor tags with jquery like this:
$('<a name="#A1"></a>').insertBefore('#header');
$('<a name="#A2">Tag #2.</a>').insertBefore('#services');
$('<a name="#A3">Tag #3.</a>').insertBefore('#portfolio');
$('<a name="#A4">Tag #4.</a>').insertBefore('#clients');
The code works, but when I try to scroll, nothing happens on the page.
I used this code that you can also see in my codepen
JS:
(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a= document.getElementsByTagName('a');
if(wd < 0) {
for(var i = 0 ; i < a.length ; i++) {
var t = a[i].getClientRects()[0].top;
if(t >= 40) break;
}
}
else {
for(var i = a.length-1 ; i >= 0 ; i--) {
var t = a[i].getClientRects()[0].top;
if(t < -20) break;
}
}
$('html,body').animate({
scrollTop: a[i].offsetTop
});
});
})();
How can I make the jquery Work?
I inspected the site and see this error duplicating everytime I try to scroll.
Here is the site am trying to test.
It is throwing error on this line of code -
var t = a[i].getClientRects()[0].top;
because a[i] for
<a href="#" class="zn-res-trigger zn-menuBurger zn-menuBurger--3--s zn-
menuBurger--anim1" id="zn-res-trigger">
<span></span>
<span></span>
<span></span>
</a>
don't have getClientRects() method.
So replace your code with
for(var i = 0 ; i < a.length ; i++) {
if(!a[i].className.includes('zn-res-trigger')) //add this check{
var t = a[i].getClientRects()[0].top;
...........
}
}
Also check with the help of debugger, may be there are other unused anchor tags, so you have to include check for them also
You have some a element that does not have top property which cause the undefined error.
try the bellow code in which I do check the a[i].getClientRects().length in order to get the top value :
(function() {
var delay = false;
$(document).on('mousewheel DOMMouseScroll', function(event) {
event.preventDefault();
if(delay) return;
delay = true;
setTimeout(function(){delay = false},200)
var wd = event.originalEvent.wheelDelta || -event.originalEvent.detail;
var a= document.getElementsByTagName('a');
var scroll = false;
if(wd < 0) {
for(var i = 0 ; i < a.length ; i++) {
if(a[i].getClientRects().length>0) {
scroll = true;
var t = a[i].getClientRects()[0].top;
if(t >= 40) break;
}
}
}
else {
for(var i = a.length-1 ; i >= 0 ; i--) {
if(a[i].getClientRects().length>0) {
scroll = true;
var t = a[i].getClientRects()[0].top;
if(t < -20) break;
}
}
}
if(scroll){
$('html,body').animate({
scrollTop: a[i].offsetTop
});
}
});
})();

jQuery plugin that bind mousedown prevent click in client code

I have plugin jQuery-splitter that bind to document.documentElement:
$(document.documentElement).bind('mousedown.splitter touchstart.splitter', function(e) {
if (splitter_id !== null) {
current_splitter = splitters[splitter_id];
$('<div class="splitterMask"></div>').css('cursor', current_splitter.children().eq(1).css('cursor')).insertAfter(current_splitter);
current_splitter.settings.onDragStart(e);
}
}).bind('mouseup.splitter touchend.splitter touchleave.splitter touchcancel.splitter', function(e) {
if (current_splitter) {
$('.splitterMask').remove();
current_splitter.settings.onDragEnd(e);
current_splitter = null;
}
}).bind('mousemove.splitter touchmove.splitter', function(e) {
if (current_splitter !== null) {
var limit = current_splitter.limit;
var offset = current_splitter.offset();
if (current_splitter.orientation == 'vertical') {
var pageX = e.pageX;
if(e.originalEvent && e.originalEvent.changedTouches){
pageX = e.originalEvent.changedTouches[0].pageX;
}
var x = pageX - offset.left;
if (x <= current_splitter.limit) {
x = current_splitter.limit + 1;
} else if (x >= current_splitter.width() - limit) {
x = current_splitter.width() - limit - 1;
}
if (x > current_splitter.limit &&
x < current_splitter.width()-limit) {
current_splitter.position(x, true);
current_splitter.find('.splitter_panel').
trigger('splitter.resize');
//e.preventDefault();
}
} else if (current_splitter.orientation == 'horizontal') {
var pageY = e.pageY;
if(e.originalEvent && e.originalEvent.changedTouches){
pageY = e.originalEvent.changedTouches[0].pageY;
}
var y = pageY-offset.top;
if (y <= current_splitter.limit) {
y = current_splitter.limit + 1;
} else if (y >= current_splitter.height() - limit) {
y = current_splitter.height() - limit - 1;
}
if (y > current_splitter.limit &&
y < current_splitter.height()-limit) {
current_splitter.position(y, true);
current_splitter.find('.splitter_panel').
trigger('splitter.resize');
//e.preventDefault();
}
}
current_splitter.settings.onDrag(e);
}
});
And in user code when I use this code the click don't work when I click on splitter (div between panels) it work when I click on the panel.
var counter = 0;
$(document.documentElement).on('click', function(e) {
console.log('x');
var $target = $(e.target);
if ($target.is('.vsplitter, .hsplitter')) {
if (++counter == 2) {
console.log('double click');
$target.parents('.splitter_panel').eq(0).data('splitter').position(20);
counter = 0;
}
} else {
counter = 0;
}
});
When I comment out the $(document.documentElement).bind('mousedown.splitter touchstart.splitter' code I can double click on the splitter. Anybody have a clue why is this happening?
It was caused by .splitterMask div.

Javascript scroll issue in Opencart theme

I'm working on a project based on Opencart with the theme Tranda Social (I think it's deprecated). The problem I'm facing is that at Home page ONLY I can't get the scroll-effects (eg. When scrolling-down keep the navbar in fixed position, or getting to the TOP by just clicking the button with the UP-arrow). After some research I've concluded that for some reason a Javascript function isn't get called correctly.
setTimeout(function () {
/* Menu */
$('#menu ul > li > a + div').each(function (index, element) {
var menu = $('#menu').offset();
var dropdown = $(this).parent().offset();
i = (dropdown.left + $(this).outerWidth()) - (menu.left + $('#menu').outerWidth());
if (i > 0) {
$(this).css('margin-left', '-' + (i + 5) + 'px');
}
});
/* Fixed Menu */
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#bottomh').offset().top;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#bottomh').addClass('bottomfixed');
} else {
$('#bottomh').removeClass('bottomfixed');
}
});
}
});
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#bottomh').offset().top;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#bottomh').addClass('bottomfixed');
} else {
$('#bottomh').removeClass('bottomfixed');
}
});
}
});
/* Margin Menu */
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#bottomh').offset().top;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#container').addClass(' topmargin');
} else {
$('#container').removeClass(' topmargin');
}
});
}
});
$(function () {
var msie6 = $.browser == 'msie' && $.browser.version < 7;
if (!msie6) {
var top = $('#bottomh').offset().top;
$(window).scroll(function (event) {
var y = $(this).scrollTop();
if (y >= top) {
$('#container').addClass(' topmargin');
} else {
$('#container').removeClass(' topmargin');
}
});
}
});
}, 500);
The functions after fixed-menu and margin-menu comments are NOT working when I'm navigating in Home page. Also if you notice, there is a duplicate of each function (don't know for what reason). Have you any ideas? Any help will be greatly appreciated.
It was a problem caused by Slidesshow module (Nivo Slider) because of a JS error related to it. Uninstall-reinstall the module fixes the problem.

Categories