.addClass() not working outside of JS Fiddle [duplicate] - javascript

This question already has answers here:
Code works in fiddle, but not on webpage
(2 answers)
Closed 9 years ago.
I'm trying to add a class to all instances of the .column class that are in the viewport.
This JS Fiddle add a class .swoosh to all .column in the viewport, but when I use the same exact js with my markup it does not add the .swoosh class to the .column in the viewport.
I checked if jquery is loading and it is.
The code is valid because it works on JS Fiddle
But for some reason, the .column in the viewport in this page are not getting the class .swoosh.
Here is the JS Fiddle again.
Here is the live page again.
Here is the code I am trying to run:
function isElementInViewport(el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document. documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document. documentElement.clientWidth)
);
}
$.fn.checkViewportAndSetClass = function() {
$(this).each(function(){
if (isElementInViewport(this)) {
$(this).addClass("swoosh");
}
});
};
$('.column').checkViewportAndSetClass();
$(window).on("scroll", function() {
$('.column').checkViewportAndSetClass();
});

You aren't including jQuery on your page. In the console: 'Uncaught ReferenceError: $ is not defined '. You can link to the google cdn copy by adding the following to your <head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

You aren't loading the jquery library in your live page. Also, you should wrap your code in a
$(document).ready(function() {
})

Related

Howto: add class when section is in viewport

I am trying to get a drawing animation effect similar to https://stackoverflow.com/a/45378478 (Preview: https://codepen.io/jbanegas/pen/LjpXom) to load when the user scrolls to this section of the page. It's intended to add multiple of these drawing boxes as the user navigates the page.
I realize that jQuery is sort of outdated now, but this is on a WordPress website that already utilizes this framework.
jQuery
<script type='text/javascript'>
$(document).ready(function(){
$('.thisisatest').addClass('draw');
});
</script>
HTML
<div class="thisisatest"></div>
I've tried replacing the .ready() with:
onload - https://www.w3schools.com/jsref/event_onload.asp
.scroll() - https://api.jquery.com/scroll/
Any help would be greatly appreciated.
You are missing the basics. Apart from adding on scroll event you need to find out if element is in view port obviously.
Here is vanilla JS solution...
It will work on all div's with content and .thisisatest class.
References Read the link on how the isInViewport function work.
var isInViewport = function(elem) {
var distance = elem.getBoundingClientRect();
return (
distance.top >= 0 &&
distance.left >= 0 &&
distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
distance.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
// read the link on how above code works
var findMe = document.querySelectorAll('.thisisatest');
window.addEventListener('scroll', function(event) {
// add event on scroll
findMe.forEach(element => {
//for each .thisisatest
if (isInViewport(element)) {
//if in Viewport
element.classList.add("draw");
}
});
}, false);
EXAMPLE: jsfiddle

How to know what part of HTML is the user on

so I want to know how I can get what section or part of my html I’m currently on. An example
So how do I know if a user has already scrolled down over part 2 using JavaScript
Or if they’re currently at part 1
<html>
<head>
</head>
<body>
<section class=“part 1”>
</section>
<section class= “part2>
</section>
</body>
</html>
The following codes will give you a little idea about how to handle this situation. Essentially you are going to want to get the scrollbar position which you can do using:
document.documentElement.scrollTop
You also want to get a range where the element you are looking for resides, in our case, it is .part1 and .part2. We can get that range by using offsetTop as the beginning of the limit and offsetTop + clientHeight to determine the end.
You are going to have to keep track of the window scroll event.
The following example is generic:
$(window).scroll(function(e) {
if (document.documentElement.scrollTop > 0
&& document.documentElement.scrollTop < $('.part2').offset().top ) {
$('div').html("At part1")
} else {
$('div').html("At part2")
}
});
JSFiddle
Likewise, if you want a little bit of modularity:
$(window).scroll(function(e) {
let watchList = ['part1', 'part2', 'part3'];
let scrollTop = document.documentElement.scrollTop;
for (var classname of watchList) {
let el = document.getElementsByClassName(classname)[0];
if (scrollTop > el.offsetTop &&
scrollTop < el.offsetTop + el.clientHeight) {
$('div').html("At <strong>"+classname+"</strong>");
}
}
});
JSFiddle
The possibilities are limitless to continue and make this more useful, but I'll leave that up to you.
you can use is[":focus"] function to find which div has focus currently.
if($(".part1").is(":focus"))
{
//you code
}
else if($(".part2").is(":focus"))
{
//you code
}
you can use mouseenter function it fires when the mouse goes into that div for the first time.
$(".part1").on('mouseenter', function(){
//your command
});
you can use mouseover function to find where is mouse right now. it fires when mouse moves inside that div.
$(".part1").on('mouseover', function(){
//your command
});
You can use javascripts offsetTop functionality. This is a parameter that returns how far down from the top a div is in the number of pixels.
It can also return how far down the user has scrolled when called on the window object itself. Then it's just a matter of math. See if the user has scolled down far enough to be past the div in reference.
For example:
var part1DivOffset = document.getElementsByClassName("part 1")[0].offsetTop;
var part2DivOffset = document.getElementsByClassName("part2")[0].offsetTop;
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
This code will get you 3 variables. The first 2 lines save the offsetTop of the div's. While the third line detects how far down the user has scrolled. Then you can do math with the variables:
if(scrollTop >= part1DivOffset){
//we are past part1
}
if(scrollTop >= part2DivOffset){
//We are past part 2
}
if(scrollTop >= part1DivOffset && scrollTop < part2DivOffset){
//We are past part 1 but not past part 2
}

Infinite scroll in Elm

I am building a simple application in Elm that show just a list of divs one under the other, and I would like to add infinite scroll functionality, to add new content every time the last div of the page appears in the viewport.
Is there a way in Elm to know when a div appears in the viewport? As an alternative, in there a way to track, as a signal, the mouse scroll event?
There is currently no Elm support for scroll events, so you'll have to resort to using ports. Here's a simple example.
We need a javascript function to tell us whether the last element in the list is in the view port. We can take the isElementInViewport code from this StackOverflow answer (copied here for future reference):
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
Let's say your HTML looks something like this:
<div class="wrapper">
<div class="item">...</div>
<div class="item">...</div>
</div>
Your Elm code could have a port acting as a signal to tell us whether the last item is visible.
port lastItemVisible : Signal Bool
Now you need to wire up the port code on the Javascript side of things. This code will listen to the window.onscroll event, then check to see if the last item inside the .wrapper div is visible, and send the appropriate signal.
var app = Elm.fullscreen(Elm.Main, {
lastItemVisible: false
});
window.onscroll = function () {
var wrapper = document.getElementsByClassName("wrapper")[0];
var lastItem = wrapper.childNodes[wrapper.childNodes.length - 1];
if (isElementInViewport(lastItem)) {
app.ports.lastItemVisible.send(true);
} else {
app.ports.lastItemVisible.send(false);
}
};
If you instead just wanted a signal for tracking scroll events, there is a related StackOverflow answer here.

How do I add a class to the body using jQuery, scrollTop, and toggleClass

I have a question concerning jQuery's scrollTop functionality, and it's ability to toggle a class based on the amount of vertical scroll.
What I am trying to accomplish is on any page with a "section.banner" class, that after you scroll past the banner a class is applied to the body tag. This will allow me to change the fill colors of several SVGs that are in the site's header, as well as a fixed positioned side nav that is for pagination.
I am terrible at javascript, and have been stuck searching and trying to get this for hours. any help will be greatly appreciated. Here's the code that I'm working with now (CodeKit is telling me it is wrong, which I am not surprised). The value of 200 is just a placeholder and will be calculated by the height of a fluid image. Full disclosure, I have no idea if the brackets and parenthesis are correct.
// Header/Fixed Pagination Banner Scroll Recoloriing (toggle class)
// Check If '.banner' Exists
if( $('section.banner').length > 0) {
$('body').scrollTop(function)()
{
if $(window).scrollTop >= 200 {
$('body').toggleClass('downtown');
return false;
}
}
}
Try something like this :
if( $('section.banner').length > 0) {
$(window).scroll(function() {
{
if ($(window).scrollTop() >= $('section.banner').scrollTop()) {
$('body').toggleClass('downtown');
return false;
}
});
}
UPDATE
There was little mistake in my code : http://jsfiddle.net/t2yp15hq/
var top = $('section.banner').position().top;
if($('section.banner').length > 0) {
$(window).scroll(function() {
if ($(this).scrollTop() >= top) {
$('body').addClass('downtown');
}
else
{
$('body').removeClass('downtown');
}
});
}
It does not work with toogleClass, the background is flashing.
UPDATE
http://codepen.io/anon/pen/wBWzXy
The solution is to recalculate the top when the window is resized :
$(window).resize(function(){
top = $('section.story-intro').offset().top - 90;
});

Applying CSS based on scroll(function()

I've written a script that increases the nav menu top-margin when my website is loaded as a web app on an iPad, however I'd like to add a third condition: after the user scrolls down.
My current script:
<script type='text/javascript'>
jQuery("div").ready(function(){
if (("standalone" in window.navigator) && window.navigator.standalone) {
var array = window.navigator.userAgent.match("iPad"); if(array!=null && array.length == 1)
jQuery(".menu-secondary-wrap").css("marginTop", "20px");
};
});
</script>
I'd like to add:
jQuery(document).scroll(function(){
if(jQuery(this).scrollTop() > 175){
I'm just not sure how to do this - I can't seem to get the syntax right.
Any help would be really appreciated!
Add this script before the closing head tag
window.onscroll = function (e) {
var scrollTopVal = window.pageYOffset || document.body.scrollTop;
if(parseInt(scrollTopVal,10) > 175){
//Your Stuff Here
}
}
No need for jQuery. DEMO

Categories