Vanilla JS, Add and Remove on Class on Scroll position - javascript

Hey i am trying to add a class depending on the scroll position.
It worked in Jquery but i want to move to vanilla, it doesn't work.
What am i missing?
IF the User scrolls to position 30px it should add the class .c-logo--scrolled
Console Error:
Uncaught TypeError: Cannot read property 'add' of undefined
at add_class_on_scroll (app.min.js:17)
at app.min.js:29
var scrollPosition = window.scrollY;
var logoContainer = document.getElementsByClassName('js-logo');
window.addEventListener('scroll', function() {
scrollPosition = window.scrollY;
if (scrollPosition >= 30) {
logoContainer.classList.add('c-logo--scrolled');
} else {
logoContainer.classList.remove('c-logo--scrolled');
}
});

var logoContainer = document.getElementsByClassName('js-logo');
var logoContainer = document.getElementsByClassName('js-logo')[0];
Then:
Place your scripts in the bottom of the body.
Ensure what element is really scrolling - it's not always window.
https://developer.mozilla.org/ru/docs/Web/API/Window/scrollY - no support in IE
http://caniuse.com/#feat=classlist - partial support in IE10+

Related

Recalculate getBoundingClientRect() on resize of browser for fixed button?

In a nutshell I'm creating a sticky button that shows after the scroll position pass a target element on the page. I'm trying to calculate the distance from the top of the page to the bottom of the target element. The script below seems to work find on load but if I resize the browser the numbers are not recalculated to get the correct distance. I know I should be using another event listener like "on resize" but I can't seem to get the logic right with my current code. Any help is welcome thanks!
Current Code
$(function(){
function ctaBundle(){
//target element
var cardsContainer = document.querySelector('.card-block');
// calculate the distance from top to the bottom of target element plus padding offset
var elDistanceToTop = window.pageYOffset + cardsContainer.getBoundingClientRect().bottom - 48;
//using to only trigger on mobile using mql
var mq = window.matchMedia('(max-width: 30em)');
//function with if statement to fade in if you pass target element
$(window).on('scroll', function() {
if ($(this).scrollTop() > elDistanceToTop && mq.matches) {
$(".sticky-cta-double").fadeIn();
}else{
$(".sticky-cta-double").hide();
}
});
}
ctaBundle();
});
I think I figured it out. By removing the on scroll event in the function and adding both event listeners after the function it seems to work.
$(function(){
function ctaBundle(){
var cardsContainer = document.querySelector('.card-block');
var bundleHeader = document.querySelector('.bundle-header');
var elDistanceToTop = window.pageYOffset + cardsContainer.getBoundingClientRect().bottom - 48;
var mq = window.matchMedia('(max-width: 30em)');
if ($(this).scrollTop() > elDistanceToTop && mq.matches) {
$(".sticky-cta-double").fadeIn();
}else{
$(".sticky-cta-double").hide();
}
}
ctaBundle();
window.addEventListener('resize', ctaBundle, false);
window.addEventListener('scroll', ctaBundle, false);
});
If anyone has a better answer/logic please let me know but this seems to be working as intended now.

add element offset to jQuery offset calculations

I am rather new to jquery and i'm trying to find the right offset for a div element inside the body. I want to make this div element sticky whenever I scroll down and pass the top offset of this element.
I followed this tutorial: https://www.youtube.com/watch?v=utonytGKodc and it works but I have a metaslider in my header and the width/height of this element is left out of the calculations to find the right offset....
the result is that my element becomes a sticky element way to soon, is there a way I can manualy add the sliders coordinates (offset) to the offset calculation of the element i want to make sticky?
var offerteOffset = jQuery(".agendawrap").offset().top //+ metaslider coordinates??;
alert(offerteOffset);
jQuery(window).scroll(function() {
var scrollPos = jQuery(window).scrollTop();
if (scrollPos >= offerteOffset) {
jQuery(".agendawrap").addClass("fixed");
} else {
jQuery(".agendawrap").removeClass("fixed");
}
});
I cant believe people make such bad tutorials.
First of all: dont write jQuery all the time. Have a look at this thread.
Basically it says: use an invoking function with an own scope:
(function($) { /* all your jQuery goes here */ })(jQuery);
So you can just type $ instead of jQuery.
To your original question:
(function($) {
$(function() { // document ready...
var scrollTolerance = 50,
agendawrap = $(".agendawrap"),
offerteOffset = agendawrap.offset().top;
$(window).on('scroll', function() {
var scrollPos = $(window).scrollTop();
// OR: if (scrollPos - scrollTolerance >= offerteOffset) {
if (scrollPos + scrollTolerance >= offerteOffset) {
agendawrap.addClass("fixed");
}
else {
agendawrap.removeClass("fixed");
}
});
});
})(jQuery);

Making nav bar effects using scroll AND click in jQuery

I want a nav to highlight (or something similar) once a user clicks on it AND when a user scrolls to the corresponding section.
However, on my computer when one clicks on any of the nav events after3, only nav event 3 changes. I'm guessing this is because after one clicks on 4 or 5, the scroll bar is already at the bottom of the page, so 4 and 5 never reach the top. The only div at the top is post 3, so my code highlights nav event 3 and ignores the click.
Is there any way I can fix this? Ive tried if statements (only highlight nav event if it's at the top AND the scrollbar isn't at the bottom or the top isn't the last item).
Here is a more accurate fiddle, using a fix below showing what I am talking about. The fix now highlights on scroll, but if you click option 5, it will not highlight.
$('.option').children('a').click(function() {
$('.option').css('background-color', '#CCCCCC;');
$(this).css('background-color', 'red');
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$(window).scrollTop(postLocation);
});
$(window).scroll(function() {
var scrollBar = $(this).scrollTop();
var allPosts = [];
var post = $('.content').offset();
var lastPost = allPosts.legnth-1
var windowHeight = $(window).height();
var bottomScroll = windowHeight-scrollBar;
$(".content").each(function(){
allPosts.push($(this).attr('id'));
});
i = 0;
for(i in allPosts){
var currentPost = "#"+allPosts[i];
var postPosition = $(currentPost).offset().top;
if (scrollBar >= postPosition){
$('.option').css('background-color', '#CCCCCC');
$('#nav'+allPosts[i]).css('background-color', 'red');
};
};
});
I think you've overdone your scroll() handler, to keep it simple you just needs to check if the scrollbar/scrollTop reaches the '.contents' offset top value but should not be greater than its offset().top plus its height().
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
$(".content").each(function (index) {
var elTop = $(this).offset().top;
var elHeight = $(this).height();
if (scrollBar >= elTop - 5 && scrollBar < elTop + elHeight) {
/* $(this) '.content' is the active on the vewport,
get its index to target the corresponding navigation '.option',
like this - $('.Nav li').eq(index)
*/
}
});
});
And you actually don't need to set $(window).scrollTop(postLocation); because of the default <a> tag anchoring on click, you can omit that one and it will work fine. However if you are looking to animate you need first to prevent this default behavior:
$('.option').children('a').click(function (e) {
e.preventDefault();
var postId = $($(this).attr('href'));
var postLocation = postId.offset().top;
$('html, body').animate({scrollTop:postLocation},'slow');
});
See the demo.
What you are trying to implement from scratch, although commendable, has already been done by the nice folks at Bootstrap. It is called a Scrollspy and all you need to do to implement it is include Bootstrap js and css (you also need jquery but you already have that) and make some minor changes to your html.
Scrollspy implementation steps.
And here is a demonstration. Notice only one line of js. :D
$('body').scrollspy({ target: '.navbar-example' });

Native Android browser not showing div at jquery.mobile

On the Chrome browser, I get everything working, but, if I want to make it work at the native Android Browser, I can't see the div I want to show. Instead, it shows me the first span with the class leftscroller.
How could this be? I tried Android 4.1.2 and 4.1.3 browsers.
This is the JS code:
$('.navigation-block').on('click', function(){
$(this).parents('#navigation.small').toggleClass('open');
});
/* Scrollable */
var showScrollIndicators = function() {
var subnav = $('#navigation.small .subnav')
if (subnav.length > 0) {
var scrollLeft = subnav.scrollLeft();
var viewportWidth = subnav.innerWidth();
var scrollWidth = subnav[0].scrollWidth;
var leftScroller = $('#navigation.small').find('.leftscroller'),
rightScroller = $('#navigation.small').find('.rightscroller');
leftScroller.addClass('enabled');
rightScroller.addClass('enabled');
if (scrollLeft === 0) {
// we've reached the far left part of the scroll area
leftScroller.removeClass('enabled');
}
if (scrollWidth - scrollLeft <= viewportWidth) {
// we've reached the far right part
rightScroller.removeClass('enabled');
}
}
};
/* Add scroll indicators */
$('#navigation.small .ph_subnav').append(
'<span class="leftscroller">You can scroll to the left</span>' +
'<span class="rightscroller">You can scroll to the right</span>'
);
showScrollIndicators();
$('#navigation.small .subnav').scroll(function() {
showScrollIndicators();
});
What am I doing wrong? So the whole area which falls beneath /Scrollable/ is not shown.

Div stops at the top when scrolling

I am trying to make a div change class to fixed when it reach the top of the page.
I have this JavaScript code.
<script type="text/javascript">
$(function () {
var top = 200;
var y = $(this).scrollTop();
if (y >= top) {
// if so, add the fixed class
$('#kolonne-v').addClass('fixed');
} else {
// otherwise remove it
$('#kolonne-v').removeClass('fixed');
}
});
</script>
What am i doing wrong?
Demo jsFiddle
JS
$(function () {
var top = 200;
//this should be the offset of the top of your div
//which can be found by doing the following line
//var top = $("#kolonne-v").offset().top;
$(window).on('scroll', function () {
if (top <= $(window).scrollTop()) {
// if so, add the fixed class
$('#kolonne-v').addClass('fixed');
} else {
// otherwise remove it
$('#kolonne-v').removeClass('fixed');
}
})
});
Description
This uses the jquery .on('scroll', handler) method, documentation here. The basic principal is that on document.ready you set the scroll point when your div becomes fixed to the top. Then you setup an .on('scroll', handler) event that triggers whenever the window is scrolled in. If the user scrolls to your point you add the fixed CSS class.

Categories

Resources