I'm fairly new to programming and I'm working on a project,
HTML
<div class="textAnimation">
<span><h2 class="animatedHeader">Text1</h2></span>
<span
><h2 class="animatedHeader twoH">Text2</h2></span
>
<span
><h2 class="animatedHeader">Text3</h2></span
>
<span
><h2 class="animatedHeader">text4</h2></span
>
<span><h2 class="animatedHeader">text5</h2></span>
<span><h2 class="animatedHeader">text6</h2></span>
<span><h2 class="animatedHeader">text7</h2></span>
<span><h2 class="animatedHeader">text8</h2></span>
<span><h2 class="animatedHeader">text9</h2></span>
</div>
JavaScript
// Check if is in viewport & animate
const headers2 = document.querySelector(".twoH");
function elementInViewportTWO() {
let bounding = headers2.getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <=
(window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <=
(window.innerHeight || document.documentElement.clientHeight)
) {
headers2.style.opacity = 1;
} else {
headers2.style.opacity = 0.6;
}
}
setInterval(elementInViewportTWO, 10);
My questions is, how to apply this effect, given an array of 9 headings without reusing so much code, how do I make my function work with an array of elements?
(My code highlights text when a certain element is in a viewport)
Select them all with document.querySelectorAll and loop through them each time.
// Check if is in viewport & animate
const headers = document.querySelectorAll(".animatedHeader");
function elementsInViewport() {
headers.forEach(header=>{
let bounding = header.getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <=
(window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <=
(window.innerHeight || document.documentElement.clientHeight)
) {
header.style.opacity = 1;
} else {
header.style.opacity = 0.6;
}
})
}
setInterval(elementsInViewport, 10);
<div class="textAnimation">
<span><h2 class="animatedHeader">Text1</h2></span>
<span
><h2 class="animatedHeader twoH">Text2</h2></span
>
<span
><h2 class="animatedHeader">Text3</h2></span
>
<span
><h2 class="animatedHeader">text4</h2></span
>
<span><h2 class="animatedHeader">text5</h2></span>
<span><h2 class="animatedHeader">text6</h2></span>
<span><h2 class="animatedHeader">text7</h2></span>
<span><h2 class="animatedHeader">text8</h2></span>
<span><h2 class="animatedHeader">text9</h2></span>
</div>
The function you've provided evaluates the dimensions of each .animatedHeader element every 10 milliseconds. This will make your CPU work very hard and has a high chance of hurting your site's peformance. And because of setInterval it will keep on running even if you're not interacting with the site and nothing changes.
Instead, consider using the Intersection Observer API which is specifically designed to detect if elements are within a viewport whilst keeping the performance high.
const headers = document.querySelectorAll('.animatedHeader');
const intersectionCallback = entries => {
for (const { isIntersecting, target } of entries) {
if (isIntersecting) {
target.style.opacity = 1;
} else {
target.style.opacity = 0.6;
}
}
};
const observer = new IntersectionObserver(intersectionCallback);
for (const header of headers) {
observer.observe(header);
}
I am working on a university project which requires me to design a website including dynamic Javascript content. This unit is exclusively about Javascript; no Jquery or anything else is allowed until next unit.
What I am trying to accomplish is for the images in the gallery to scroll in when they are scrolled into the viewport. If any part of the image is visible, the script should begin increasing the opacity proportionally to how much of the image has been scrolled in. I've tried a few different things from different tutorial and answers in the stack, but nothing works. The code might work, but it doesn't activate on scroll. Here's the code if anyone can help:
var elementPosition = window.pageYOffset;
function isInViewport(img) {
var relct = img.getBoundingClientRect();
return rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight);
}
function fadeIn() {
var imgList = document.getElementsByTagName("IMG");
var i;
for (i = 0; i < imgList.length; i++) {
var img = imgList[i];
if (isInViewport(img)) {
if (elementPosition < 200) {
opacity = 1 - (elementPosition / 200));
}
else {
opacity = 1;
}
}
else {
opacity = 0;
}
}
}
window.addEventListener('scroll', fadeIn());
Lots of typos were fouling your code -- I'd recommend using an application that will either tidy your code and/or flag errors as you write (personally, I use codepen.io). Also, opacity is set by: element.style.opacity.
var imgList = document.getElementsByTagName("IMG");
function isInViewport(img) {
var rect = img.getBoundingClientRect();
return (
rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document.documentElement.clientWidth) &&
rect.top < (window.innerHeight || document.documentElement.clientHeight)
);
}
function fadeIn() {
for (i = 0; i < imgList.length; i++) {
if (isInViewport(imgList[i])) {
imgList[i].style.opacity = 1;
}
}
}
window.addEventListener("scroll", fadeIn);
img {display: block; transition: all 1s; opacity: 0;}
<img src="http://www.fillmurray.com/300/600">
<img src="http://www.fillmurray.com/300/600">
<img src="http://www.fillmurray.com/300/600">
<img src="http://www.fillmurray.com/300/600">
I'm trying to add and remove some classes depending on the scroll position. The problem in my code is that it's not doing my else if conditions.
Also, can I use any other measurements? Such as document.body.scrollTop < 25%
<script>
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop < 800 || document.documentElement.scrollTop < 800) {
document.querySelector(".navbar").classList.add('nav-dark');
} else if(document.body.scrollTop === 0 || document.documentElement.scrollTop === 0){
document.querySelector(".navbar").classList.add('nav-transparent');
document.querySelector(".navbar").classList.remove('nav-dark');
}
}
</script>
0 will always be less than 800; as such, you need to change the order of your statements.
if(document.body.scrollTop === 0 || document.documentElement.scrollTop === 0){
document.querySelector(".navbar").classList.add('nav-dark');
} else if (document.body.scrollTop < 800 || document.documentElement.scrollTop < 800) {
document.querySelector(".navbar").classList.add('nav-transparent');
document.querySelector(".navbar").classList.remove('nav-dark');
}
Your code can be simplified by using window.pageYOffset instead to get the vertical amount scrolled. See my answer here if you want a robust cross browser solution.
if(window.pageYOffset === 0){
document.querySelector(".navbar").classList.add('nav-dark');
} else if (window.pageYOffset < 800) {
document.querySelector(".navbar").classList.add('nav-transparent');
document.querySelector(".navbar").classList.remove('nav-dark');
}
Reverse the condition i..e move condition with 0 first and then < 800. Since 0 is also less than 800 that's why it is not going into else if block.
I have some javascript being fired when the screen reaches certain widths... I am trying to make it mobile responsive and need it to fire at different points on different devices...
var screenWidth = window.innerWidth;
if (screenWidth <= 812 && screenWidth > 414) {
$(window).scroll(function() {
var fromTopPxFirstBgChange = 2300;
var scrolledFromtop = $(window).scrollTop();
if (scrolledFromtop > fromTopPxFirstBgChange) {
$('body').addClass('secondBg');
}
else {
$('body').removeClass('secondBg');
}
});
}
if (screenWidth <= 414 && screenWidth > 375) {
$(window).scroll(function() {
var changeBg = 2190;
var scrolledFromtop = $(window).scrollTop();
if (scrolledFromtop > changeBg) {
$('body').addClass('secondBg');
}
else {
$('body').removeClass('secondBg');
}
});
}
if (screenWidth <= 375 && screenWidth > 320) {
$(window).scroll(function() {
var changeBgImage = 2380;
var scrolledFromtop = $(window).scrollTop();
if (scrolledFromtop > changeBgImage) {
$('body').addClass('secondBg');
}
else {
$('body').removeClass('secondBg');
}
});
}
So for the first one for example, I would like the screen to apply those changes at 414-812px.
Basically the background image is supposed to change when I am scrolled to the position on the page that I specified in each if statement (the class "secondBg" is a class I specified in the CSS with the new background image... I don't know if this is a JS error or a problem with other code. It seems to work uniform when I just have one if statement but when I add the three they sort of work and overwrite one another. I think the if statements are pretty clear and cannot see the problem.
You shouldn't be binding your listeners inside the if statements. You should instead have 1 listener and do checks inside like so:
$(window).scroll(function() {
if($(window).scrollTop() < 500) {
// Your code here
}
// add more checks here
});
Also, I'd throttle that as it's a really heavy operation. Take a look at this.
how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.
Live Demo
Basically you just check the position of the element to see if its within the windows viewport.
function checkIfInView(element){
var offset = element.offset().top - $(window).scrollTop();
if(offset > window.innerHeight){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset}, 1000);
return false;
}
return true;
}
Improving Loktar's answer, fixing the following:
Scroll up
Scroll to a display:none element (like hidden div's etc)
function scrollToView(element){
var offset = element.offset().top;
if(!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = $(window).scrollTop();
var visible_area_end = visible_area_start + window.innerHeight;
if(offset < visible_area_start || offset > visible_area_end){
// Not in view so scroll to it
$('html,body').animate({scrollTop: offset - window.innerHeight/3}, 1000);
return false;
}
return true;
}
After trying all these solutions and many more besides, none of them satisfied my requirement for running old web portal software (10 years old) inside IE11 (in some compatibility mode). They all failed to correctly determine if the element was visible. However I found this solution. I hope it helps.
function scrollIntoViewIfOutOfView(el) {
var topOfPage = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var heightOfPage = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var elY = 0;
var elH = 0;
if (document.layers) { // NS4
elY = el.y;
elH = el.height;
}
else {
for(var p=el; p&&p.tagName!='BODY'; p=p.offsetParent){
elY += p.offsetTop;
}
elH = el.offsetHeight;
}
if ((topOfPage + heightOfPage) < (elY + elH)) {
el.scrollIntoView(false);
}
else if (elY < topOfPage) {
el.scrollIntoView(true);
}
}
I made a slightly more generic version of digitalPBK's answer that minimally scrolls an element contained within a div or some other container (including the body). You can pass DOM elements or selectors to the function, as long as the element is somehow contained within the parent.
function scrollToView(element, parent) {
element = $(element);
parent = $(parent);
var offset = element.offset().top + parent.scrollTop();
var height = element.innerHeight();
var offset_end = offset + height;
if (!element.is(":visible")) {
element.css({"visibility":"hidden"}).show();
var offset = element.offset().top;
element.css({"visibility":"", "display":""});
}
var visible_area_start = parent.scrollTop();
var visible_area_end = visible_area_start + parent.innerHeight();
if (offset-height < visible_area_start) {
parent.animate({scrollTop: offset-height}, 600);
return false;
} else if (offset_end > visible_area_end) {
parent.animate({scrollTop: parent.scrollTop()+ offset_end - visible_area_end }, 600);
return false;
}
return true;
}
You can take a look at his awesome link from the jQuery Cookbook:
Determining Whether an Element Is Within the Viewport
Test if Element is contained in the Viewport
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
if (
(elementOffset.top > minTop && elementOffset.top + elementHeight < maxTop) &&
(elementOffset.left > minLeft && elementOffset.left + elementWidth < maxLeft)
) {
alert('entire element is visible');
} else {
alert('entire element is not visible');
}
});
Test how much of the element is visible
jQuery(document).ready(function() {
var viewportWidth = jQuery(window).width(),
viewportHeight = jQuery(window).height(),
documentScrollTop = jQuery(document).scrollTop(),
documentScrollLeft = jQuery(document).scrollLeft(),
$myElement = jQuery('#myElement'),
verticalVisible, horizontalVisible,
elementOffset = $myElement.offset(),
elementHeight = $myElement.height(),
elementWidth = $myElement.width(),
minTop = documentScrollTop,
maxTop = documentScrollTop + viewportHeight,
minLeft = documentScrollLeft,
maxLeft = documentScrollLeft + viewportWidth;
function scrollToPosition(position) {
jQuery('html,body').animate({
scrollTop : position.top,
scrollLeft : position.left
}, 300);
}
if (
((elementOffset.top > minTop && elementOffset.top < maxTop) ||
(elementOffset.top + elementHeight > minTop && elementOffset.top +
elementHeight < maxTop))
&& ((elementOffset.left > minLeft && elementOffset.left < maxLeft) ||
(elementOffset.left + elementWidth > minLeft && elementOffset.left +
elementWidth < maxLeft)))
{
alert('some portion of the element is visible');
if (elementOffset.top >= minTop && elementOffset.top + elementHeight
<= maxTop) {
verticalVisible = elementHeight;
} else if (elementOffset.top < minTop) {
verticalVisible = elementHeight - (minTop - elementOffset.top);
} else {
verticalVisible = maxTop - elementOffset.top;
}
if (elementOffset.left >= minLeft && elementOffset.left + elementWidth
<= maxLeft) {
horizontalVisible = elementWidth;
} else if (elementOffset.left < minLeft) {
horizontalVisible = elementWidth - (minLeft - elementOffset.left);
} else {
horizontalVisible = maxLeft - elementOffset.left;
}
var percentVerticalVisible = (verticalVisible / elementHeight) * 100;
var percentHorizontalVisible = (horizontalVisible / elementWidth) * 100;
if (percentVerticalVisible < 50 || percentHorizontalVisible < 50) {
alert('less than 50% of element visible; scrolling');
scrollToPosition(elementOffset);
} else {
alert('enough of the element is visible that there is no need to scroll');
}
} else {
// element is not visible; scroll to it
alert('element is not visible; scrolling');
scrollToPosition(elementOffset);
}
The following code helped me achieve the result
function scroll_to_element_if_not_inside_view(element){
if($(window).scrollTop() > element.offset().top){
$('html, body').animate( { scrollTop: element.offset().top }, {duration: 400 } );
}
}
Here is the solution I came up with, working both up and down and using only Vanilla Javascript, no jQuery.
function scrollToIfNotVisible(element) {
const rect = element.getBoundingClientRect();
// Eventually an offset corresponding to the height of a fixed navbar for example.
const offset = 70;
let scroll = false;
if (rect.top < offset) {
scroll = true;
}
if (rect.top > window.innerHeight) {
scroll = true;
}
if (scroll) {
window.scrollTo({
top: (window.scrollY + rect.top) - offset,
behavior: 'smooth'
})
}
}
There is a jQuery plugin which allows us to quickly check if a whole element (or also only part of it) is within the browsers visual viewport regardless of the window scroll position. You need to download it from its GitHub repository:
Suppose to have the following HTML and you want to alert when footer is visible:
<section id="container">
<aside id="sidebar">
<p>
Scroll up and down to alert the footer visibility by color:
</p>
<ul>
<li><span class="blue">Blue</span> = footer <u>not visible</u>;</li>
<li><span class="yellow">Yellow</span> = footer <u>visible</u>;</li>
</ul>
<span id="alert"></span>
</aside>
<section id="main_content"></section>
</section>
<footer id="page_footer"></footer>
So, add the plugin before the close of body tag:
<script type="text/javascript" src="js/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/jquery_visible/examples/js/jq.visible.js"></script>
After that you can use it in a simple way like this:
<script type="text/javascript">
jQuery( document ).ready(function ( $ ) {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
$(window).scroll(function() {
if ($("footer#page_footer").visible(true, false, "both")) {
$("#main_content").css({"background-color":"#ffeb3b"});
$("span#alert").html("Footer visible");
} else {
$("#main_content").css({"background-color":"#4aafba"});
$("span#alert").html("Footer not visible");
}
});
});
</script>
Here a demo
No-JQuery version.
The particular case here is where the scroll container is the body (TBODY, table.body) of a TABLE (scrolling independently of THEAD). But it could be adapted to any situation, some simpler.
const row = table.body.children[ ... ];
...
const bottomOfRow = row.offsetHeight + row.offsetTop ;
// if the bottom of the row is in the viewport...
if( bottomOfRow - table.body.scrollTop < table.body.clientHeight ){
// ... if the top of the row is in the viewport
if( row.offsetTop - table.body.scrollTop > 0 ){
console.log( 'row is entirely visible' );
}
else if( row.offsetTop - table.body.scrollTop + row.offsetHeight > 0 ){
console.log( 'row is partly visible at top')
row.scrollIntoView();
}
else {
console.log( 'top of row out of view above viewport')
row.scrollIntoView();
}
}
else if( row.offsetTop - table.body.scrollTop < table.body.clientHeight ){
console.log( 'row is partly visible at bottom')
row.scrollIntoView();
}
else {
console.log( 'row is out of view beneath viewport')
row.scrollIntoView();
}
I think this is the complete answer. An elevator must be able to go both up and down ;)
function ensureVisible(elementId, top = 0 /* set to "top-nav" Height (if you have)*/) {
let elem = $('#elementId');
if (elem) {
let offset = elem.offset().top - $(window).scrollTop();
if (offset > window.innerHeight) { // Not in view
$('html,body').animate({ scrollTop: offset + top }, 1000);
} else if (offset < top) { // Should go to top
$('html,body').animate({ scrollTop: $(window).scrollTop() - (top - offset) }, 1000);
}
}
}