Change Image on Scroll Position - javascript

I would like to change an image on a certain scroll position. For example:
Scroll 100px show img1.jpg
Scroll 200px show img2.jpg
Scroll 300px show img3.jpg
Here I found an example what I mean.
Any ideas?

You can use the onScroll event to listen for scrolling, check at what position the scrollbar is and make the image change or whatever your heart desires. You can read more about onScroll event here. A basic code will be something like this:
var onScrollHandler = function() {
var newImageUrl = yourImageElement.src;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 100) {
newImageUrl = "img1.jpg"
}
if (scrollTop > 200) {
newImageUrl = "img2.jpg"
}
if (scrollTop > 300) {
newImageUrl = "img3.jpg"
}
yourImageElement.src = newImageUrl;
};
object.addEventListener ("scroll", onScrollHandler);
Of course yourImageElement should be replaced with the image element you want to change.
If you have jQuery availble you can use the .scroll() method instead of the event listener and the .scrollTop() to get the scrollbar position.
Also, you might want to look at some scroll/paralex libraries like skrollr.

$(window).on("scroll touchmove", function()
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top )
{
$('body').css('background-image', 'url(https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(https://i1.wp.com/cdn.catawiki.net/assets/marketing/uploads-files/45485-8bdcc8479f93d5a247ab844321b8b9d5e53c49a9-story_inline_image.jpg)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top )
{
$('body').css('background-image', 'url(https://s-media-cache-ak0.pinimg.com/originals/e1/7a/03/e17a0385726db90de1854177d4af2b4f.jpg)')
};
if ($(document).scrollTop() >= $("#four").position().top)
{
$('body').css('background-image', 'url(https://www.wallpaperup.com/uploads/wallpapers/2015/02/13/621414/6fc33c3ae65a58f9bb137f5cf011aebc.jpg)')
};
});
*{
margin:0;
padding:0;
}
.main{
width:100%;
height:100vh;
background-image:url('https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>
documentation
create a web folder first.
create a img sub folder // place all images into this folder
now create three files // in web folder
index.html
css.css
js.js
copy code given bellow and paste it.
save the program.
finally run the program
click on this link to see the video :https://www.youtube.com/watch?v=V97wCVY_SrQ
visit our website for full documentation :https://nozzons.blogspot.com/
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='css.css' rel='stylesheet' type='text/css'/>
<script src='js.js'></script>
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>
css.css
*{
margin:0;
padding:0;
}
.main{
width:100%;
height:100vh;
background-image:url('img/img_one.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
js.js
$(window).on("scroll touchmove", function()
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top )
{
$('body').css('background-image', 'url(img/img_one.jpg)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(img/img_two.jpg)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top )
{
$('body').css('background-image', 'url(img/img_three.jpg)')
};
if ($(document).scrollTop() >= $("#four").position().top)
{
$('body').css('background-image', 'url(img/img_four.jpg)')
};
});

So i am just answering this old thread because I was trying to implement the same thing on my website but i found it a bit difficult to implement it so I made a function of my own , its a bit easier to implement and understand but a bit buggy, For instance: if the user use the scroll bar instead of scroll wheel of the mouse the image will not change , hope it helps you :
<html>
<head>
<script>
function f() {
t1.src = "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg"
t1.height = "319"
t1.width = "330"
}
function f2() {
t1.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG"
t1.height = "319"
t1.width = "330"
}
function f3() {
t1.src = "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg"
t1.height = "244"
t1.width = "330"
}
function f4() {
t1.src = "https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg"
t1.height = "244"
t1.width = "350"
}
function f5() {
t1.src = "http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
t1.height = "319"
t1.width = "350"
}
</script>
</head>
<body>
<div align="center" style="position: fixed; z-index: 20; left:38.5%; top:200">
<img src="no.png" height="319" width="330" name="t1">
</div>
</div>
<div class="container" onmouseover="f3()" style="padding:0; margin:0; width:100%;">
<img src="https://pixabay.com/static/uploads/photo/2016/01/11/22/05/background-1134468_960_720.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f4()" style="padding:0; margin:0; width:100%;">
<img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f5()" style="padding:0; margin:0; width:100%;">
<img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f()" style="padding:0; margin:0; width:100%;"></div>
</body></html>
Cheers!!
Ha[ppy] Coding.

Related

How to hide/show fixed element in some sections in my html page? [duplicate]

This question already has answers here:
How to hide/show a fixed element when scrolling some sections into view vertically?
(2 answers)
Closed 5 months ago.
I want that fixed element #logoimode3 show/hide on some sections.
Example: Show #logoimode3 on #section2 and #section3 Hide #logoimode3 on #section1 and #section4
And need to hide also in small screen.
So fixed element have to disapear on blue section. And than show again on green section. I want my logo to disapear while scrolling trought section 2.
<!DOCTYPE html>
<html>
<head>
<style></style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
jQuery(document).ready(function() {
var sec2 = document.getElementById("section2");
var pos = sec2.getBoundingClientRect();
var height1 = pos.height * -1;
if (pos.top < 1 && pos.top > height1) {
jQuery('#logoimode3').hide();
}
else if(pos.top < height1 || pos.top > 1) {
jQuery('#logoimode3').show();
}
});
jQuery(window).scroll(function() {
var sec2 = document.getElementById("section2");
var pos = sec2.getBoundingClientRect();
var height1 = pos.height * -1;
if (pos.top < 1 && pos.top > height1) {
jQuery('#logoimode3').hide();
}
else if(pos.top < height1 || pos.top > 1) {
jQuery('#logoimode3').show();
}
});
</script>
</head>
<body>
<img id="logoimode3" class="logo3" style="position:fixed;top:0px;left:0px;" src="https://imode.info/imode/slike/ikone/IMODE_znak-01.svg" alt="logo" height="" width="30px">
<section id="section1" style="background: red; height:100vh;"></section>
<section id="section2" style="background: blue; height:100vh;"></section>
<section id="section3" style="background: green; height:100vh;"></section>
<section id="section4" style="background: pink; height:100vh;"></section>
</body>
<footer></footer>
</html>
here i have added code for
$(document).ready(function(){
$("#hide").click(function(){
$("div").hide(1000);
});
$("#show").click(function(){
$("div").show(1000);
});
});
div{
width:100px;
height:100px;
border-radius:50%;
background-color:#9081c6;
display:flex;
align-self:center;
align-items: center;
justify-content: center;
font-size:14px;
margin-bottom:15px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>jquery</div>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
showing and hiding div on click with animation effect
Please try below code :
<html>
<head>
<style></style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
jQuery(document).ready(function() {
jQuery('#logoimode3').hide();
});
$(document).scroll(function () {
$('section').each(function () {
if($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
if($(this).attr('id') == "section1" || $(this).attr('id') == "section4")
{
jQuery('#logoimode3').hide();
}
else
{
jQuery('#logoimode3').show();
}
}
});
});
</script>
</head>
<body>
<img id="logoimode3" class="logo3" style="position:fixed;top:0px;left:0px;" src="https://imode.info/imode/slike/ikone/IMODE_znak-01.svg" alt="logo" height="" width="30px">
<section id="section1" style="background: red; height:100vh;"></section>
<section id="section2" style="background: blue; height:100vh;"></section>
<section id="section3" style="background: green; height:100vh;"></section>
<section id="section4" style="background: pink; height:100vh;"></section>
</body>
<footer></footer>
</html>
For Demo : https://jsfiddle.net/fxjL7gmw/1/

How to make infinite Scrolling?

I am creating a Slider with horizontal Scrolling effect But I stuck at a point how Can I make the slider scroll infinitely Like in my code you can see After Item 6 it stops Scrolling and I have to scroll backward but I want it like after Item 6, Item 1 will come again Something like this https://durimel.io/nel Here you can see the scrolling is infinite?
So can anyone help in this?
let container = document.querySelector(".container")
let container1 = document.querySelector(".container1")
window.onscroll = ()=>{
container.style.left = `${-window.scrollY}px`
container1.style.right = `${-window.scrollY}px`
}
let currentpos = container.getBoundingClientRect().left
let currentpos1 = container1.getBoundingClientRect().left
let callDisort = () =>{
let newPos = container.getBoundingClientRect().left;
let newPos1 = container1.getBoundingClientRect().left;
let diff = newPos - currentpos;
let speed = diff * 0.50
container.style.transform = `skewX(${speed}deg)`
currentpos = newPos
container1.style.transform = `skewX(${speed}deg)`
currentpos = newPos
requestAnimationFrame(callDisort)
}
console.log(currentpos)
callDisort()
*{
margin:0;
padding:0;
box-sizing:border-box;
font-family: arial;
}
html,body{
height:3000px;
overflow-X:hidden;
}
.container{
position:fixed;
display:flex;
justify-content: space-between;
top:30vh;
width: 3000px;
transition:transform 0.15s;
will-change:transform;
border:2px solid green;
}
.container1{
position:fixed;
display:flex;
justify-content: space-evenly;
top:45vh;
width: 3000px;
transition:transform 0.15s;
will-change:transform;
border:2px solid green;
}
.box{
position:relative;
}
.box h2{
font-size:4em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="box one">
<h2>Item 1</h2>
</div>
<div class="box two">
<h2>Item 2</h2>
</div>
<div class="box three">
<h2>Item 3</h2>
</div>
<div class="box four">
<h2>Item 4</h2>
</div>
<div class="box five">
<h2>Item 5</h2>
</div>
<div class="box six">
<h2>Item 6</h2>
</div>
</div>
<div class="container1">
<div class="box one">
<h2>Item 1</h2>
</div>
<div class="box two">
<h2>Item 2</h2>
</div>
<div class="box three">
<h2>Item 3</h2>
</div>
<div class="box four">
<h2>Item 4</h2>
</div>
<div class="box five">
<h2>Item 5</h2>
</div>
<div class="box six">
<h2>Item 6</h2>
</div>
</div>
</body>
</html>
The method the example (https://durimel.io/nel) uses differs and is not really infinite. It is limited to the max values the css properties left and transform: translate3d() support. But its enough for a normal use.
It changes the position of each box as soon as it is out of view depending on the direction and moving it behind the "last" or before the "first" using transform: translate3d() and left: ....
Overall here is version of the method i mentioned. I recommend testing it in on jsfiddle or run the snippet in "Full Page"-View because of the mouse-wheel-scrolling behavior from unscrollable iframe-childs and a scrollable parents can't be prevented.
Update:
Added a simple speed detection routine to allow faster/slower scrolling.
Also fixed the selector for the observer at the end of the js part
const eventHandler = (e) => {
document.querySelectorAll(".boxes-container").forEach(container => {
const cur = +container.dataset.cur || 0;
container.dataset.before = container.dataset.cur;
container.dataset.scrollspeed = (+container.dataset.scrollspeed || 0) +1;
setTimeout(() => {
container.dataset.scrollspeed = +container.dataset.scrollspeed -1;
}, 33 * +container.dataset.scrollspeed);
let moveByPixels = Math.round(e.deltaY / (6 - Math.min(+container.dataset.scrollspeed,5)));
if (container.dataset.direction == "invert") {
moveByPixels *= -1;
}
container.style.left = `${cur + -moveByPixels}px`;
container.dataset.cur = cur + -moveByPixels;
});
};
window.addEventListener("wheel", eventHandler);
window.addEventListener("mousewheel", eventHandler);
const observer = new IntersectionObserver((entries, opts) => {
entries.forEach(entry => {
entry.target.classList.toggle('visible', entry.isIntersecting);
});
document.querySelectorAll(".boxes-container").forEach(container => {
const before = (+container.dataset.before || 0),
current = (+container.dataset.cur || 0),
diff = before - current,
boxes = [...container.querySelectorAll(".box")],
visible = [...container.querySelectorAll(".box.visible")],
first = boxes.indexOf(visible[0]),
last = boxes.indexOf(visible[visible.length - 1]),
adjust = (by) => {
container.dataset.cur = +container.dataset.cur + by;
container.dataset.before = +container.dataset.before + by;
container.style.left = +container.dataset.cur + 'px';
};
if (diff >= 0) {
if (first > 0) { // move the first to the end
const box = boxes[0];
box.parentNode.append(box);
adjust(box.clientWidth);
}
} else {
if (last == 0 || first == 0) { // move the to first
const box = boxes[boxes.length - 1];
box.parentNode.prepend(box);
adjust(-box.clientWidth);
}
}
})
}, { // trigger on any percent value
threshold: new Array(101).fill(0).map((n, i) => +(i / 100).toFixed(2))
});
document.querySelectorAll(".boxes-container .box").forEach(el => observer.observe(el));
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Sans-Serif;
}
.boxes-container {
position: fixed;
display: flex;
flex-wrap: nowrap;
flex-direction: row;
white-space: nowrap;
min-width: -min-content;
}
.v30 {
top: 30vh;
}
.v60 {
top: 60vh;
}
.box {
position: relative;
margin: 0 !important;
padding: 0 50px;
}
.box h2 {
font-size: 5rem;
}
<div class="boxes-container">
<div class="box">
<h2>0</h2>
</div>
<div class="box">
<h2>1</h2>
</div>
<div class="box">
<h2>2</h2>
</div>
<div class="box">
<h2>3</h2>
</div>
<div class="box">
<h2>4</h2>
</div>
<div class="box">
<h2>5</h2>
</div>
<div class="box">
<h2>6</h2>
</div>
</div>
<div class="boxes-container v30" data-direction="invert">
<div class="box">
<h2>A</h2>
</div>
<div class="box">
<h2>B</h2>
</div>
<div class="box">
<h2>C</h2>
</div>
<div class="box">
<h2>D</h2>
</div>
<div class="box">
<h2>E</h2>
</div>
<div class="box">
<h2>F</h2>
</div>
<div class="box">
<h2>G</h2>
</div>
</div>
<div class="boxes-container v60">
<div class="box">
<h2>0</h2>
</div>
<div class="box">
<h2>1</h2>
</div>
<div class="box">
<h2>2</h2>
</div>
<div class="box">
<h2>3</h2>
</div>
<div class="box">
<h2>4</h2>
</div>
<div class="box">
<h2>5</h2>
</div>
<div class="box">
<h2>6</h2>
</div>
</div>
A few comments on this solution.
If the container is set to display:flex; justify-content:space-around; then the space between the items will change as you scroll (the more items, the closer packed they are). Changing to justify-content:flex-start; with a fixed width for each .box delivers the best result.
Adding a debounce fn greatly improved (and simplified) the job. At least, the console logs are underwhelming(!).
If you scroll the scroll wheel very fast, you might hit the end of the carousel before it re-populates. To make that easier to see, change the delay from 50 to 500 (milliseconds).
The debounce is saying, "only plunk more boxes into the container when 50ms has elapsed since the last scroll event. You might prefer a throttle function instead, where it will run at most one re-population every 50ms (or as you set the debounceDelay value).
The HTML,Body height needs to be set to a very large number - in this demo it is now set to 30,000. The .container width should be auto, and it (the .container width) will increase every time new items are plonked into the container.
Most important: the $ and $$ are not jQuery. They are pure vanilla javaScript shorthand for document.querySelector() and document.querySelectorAll()
The demo is best viewed full page (link at top right of demo window).
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
let kontainer = $(".container");
const boxes = $$('.box');
const debounceDelay = 50; //change to 100 for better performance
const updateCarousel = debounce(function(e){
console.log(scrollY +' // '+ kontainer.getBoundingClientRect().right)
const currKontainerWidth = kontainer.getBoundingClientRect().right;
if ( currKontainerWidth - scrollY < 300 ){
for (let i=0, j=boxes.length; j > i; i++){
kontainer.appendChild(boxes[i].cloneNode(true));
}
}
}, debounceDelay);
window.addEventListener('scroll', updateCarousel, false);
window.onscroll = () => {
kontainer.style.left = `${-window.scrollY}px`;
}
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
*{
margin:0;
padding:0;
box-sizing:border-box;
font-family: arial;
}
html,body{
height:30000px;
overflow-X:hidden;
}
.container{
position:fixed;
display:flex;
justify-content: flex-start;
top:30vh;
width: auto;
transition:transform 0.15s;
will-change:transform;
border:2px solid green;
}
.box{
position:relative;
min-width:250px;
}
.box h2{
font-size:4em;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="box one">
<h2>Item 1</h2>
</div>
<div class="box two">
<h2>Item 2</h2>
</div>
<div class="box three">
<h2>Item 3</h2>
</div>
<div class="box four">
<h2>Item 4</h2>
</div>
<div class="box five">
<h2>Item 5</h2>
</div>
<div class="box six">
<h2>Item 6</h2>
</div>
</div>
</body>
</html>
Best viewed "full page" (top right link after clicking Run Code Snippet)

Change image during scroll when the text becomes visible

I have this script that changes the image(s) when the text reaches the top of the screen. I want it in reverse. I would like to have the image(s) change when the text becomes visible from a certain height (say 50px) from bottom. How do I go about this?
JS Fiddle: https://jsfiddle.net/ramo427e/
HTML:
<div class="main">
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>This is sparta and what comes whatever after. This is sparta and what comes whatever after. This is sparta and what comes whatever after. </h1><h1>This is sparta and what comes whatever after. This is sparta and what comes whatever after. This is sparta and what comes whatever after. </h1>
</div>
<div class="col-md-6">
<section id="one">
<div class="content">
<h1>first heading</h1>
<p>description</p>
</div>
</section>
<section id="two">
<div class="content">
<h1>second heading</h1>
<p>description</p>
</div>
</section>
<section id="three">
<div class="content">
<h1>third heading</h1>
<p>description</p>
</div>
</section>
<section id="four">
<div class="content">
<h1>fourth heading</h1>
<p>description</p>
</div>
</section>
</div>
<div class="col-md-6">
<div class="image"></div>
</div>
</div>
<div class="row">
<div class="col-12">
<h1>This is sparta and what comes whatever after. This is sparta and what comes whatever after. This is sparta and what comes whatever after. </h1>
</div>
</div>
</div>
</div>
CSS:
*{
margin:0;
padding:0;
}
h1{
font-size: 18px;
font-weight: strong;
}
p{
font-size: 12px;
}
.main{
width:100%;
height:auto;
position: relative;
}
.image {
background-image:url('https://i.postimg.cc/FRxNp6yG/hr-ax.png');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
width: 200px;
height: 200px;
position: fixed;
}
#one, #two, #three, #four {
min-height: 150px;
}
JS:
$(window).on("scroll touchmove", function() {
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top) {
$('.image').css('background-image', 'url(https://i.postimg.cc/FRxNp6yG/hr-ax.png)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top) {
$('.image').css('background-image', 'url(https://i.postimg.cc/wvz9hzm7/hr-bx.png)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top) {
$('.image').css('background-image', 'url(https://i.postimg.cc/FRxNp6yG/hr-ax.png)')
};
if ($(document).scrollTop() >= $("#four").position().top) {
$('.image').css('background-image', 'url(https://i.postimg.cc/wvz9hzm7/hr-bx.png)')
};
});
on the scroll, you can get the position of the all element. And calculate whether it is visible or not. Based on the switch case you can change image.
Sample:
window.addEventListener('scroll', function() {
var element = document.querySelector('#main-container');
var position = element.getBoundingClientRect();
// checking whether fully visible
if(position.top >= 0 && position.bottom <= window.innerHeight) {
console.log('Element is fully visible in screen');
}
// checking for partial visibility
if(position.top < window.innerHeight && position.bottom >= 0) {
console.log('Element is partially visible in screen');
}
});
More:
https://usefulangle.com/post/113/javascript-detecting-element-visible-during-scroll
Select the text with jQuery and correct the height relative to that and use that to trigger the event for Example:
if($(document).scrollTop() >= $("#one .content h1").position().top - 50){
$('.image').css('background-image', 'url(https://i.postimg.cc/FRxNp6yG/hr-ax.png)')
}

Viewport - jQuery selectors for finding elements in viewport

In my project every div has a video so I'm trying to check if a div is in viewport, so if it is that video to start playing and if it's not to pause or to stop. I'm jusing jekyll.
For example my html code for only one div looks like this :
<div class="container">
<div class="row">
<input type="button" id="play" value="Play"></input>
<input type="button" id="pause" value="Pause"></input>
<br/><br/>
<div class="col-lg-5 col-lg-offset-1 col-sm-push-6 col-sm-6">
<hr class="section-heading-spacer">
<div class="clearfix"></div>
<h2 class="section-heading">Vjetersia</h2>
<div class="lead"><p class="justify"> Vjetersia</p></div>
</div>
<div class="col-lg-5 col-sm-pull-6 col-sm-6">
<div class="gifv-player" id="">
<video preload="none" loop="loop">
<source type="video/webm" src="all_files/1.webm" />
</video>
<img src="example.png" alt="Animated Gif" />
</div>
</div>
<div class="col-lg-3 col-sm-pull-2 col-sm-2"></div>
</div>
</div>
I tried to do it on button click and it works:
$( document ).ready(function() {
player = new GifvPlayer();
$("#play").click(function() {
$('.gifv-player').find('video').show();
$('.gifv-player').find('video')[0].play();
});
$("#pause").click(function() {
$('.gifv-player').find('video')[0].pause();
});
});
but how can i modify it so it can work on stroll if a div is visible to start to play its video ? Any help?
easy quick and dirty example how you could implement it. play/pause like changing colors of the divs ... http://jsfiddle.net/7mkdj4ak/1/
var scrollPosition = $(window).scrollTop();
var windowViewHeight = $(window).height();
var videoWrapHeight = $('.container').outerHeight();
$(window).on('scroll', function(){
scrollPosition = $(window).scrollTop();
playVideos(scrollPosition);
});
$(window).on('resize', function(){
windowViewHeight = $(window).height();
});
var playVideos = function(scrollPosition) {
$('.container').each(function(i){
var thisContainerTopPosition = $(this).offset().top;
var thisContainerBottomPosition = thisContainerTopPosition + videoWrapHeight;
if(
thisContainerTopPosition >= scrollPosition &&
thisContainerBottomPosition <= (scrollPosition + windowViewHeight )
) {
/* div is in view PLaY */
$(this).css('background-color','orange');
} else {
/* div is out of view PausE */
$(this).css('background-color','#afafaf');
}
});
};
playVideos(scrollPosition);
.container {
width: 100%;
height: 100px;
background-color: #afafaf;
margin: 20px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1>my Video 1</h1>
</div>
<div class="container">
<h1>my Video 2</h1>
</div>
<div class="container">
<h1>my Video 3</h1>
</div>
<div class="container">
<h1>my Video 4</h1>
</div>
You can refer this demo
.growme {
background-color: #990000;
height: 0;
width: 0;
position: absolute;
filter: alpha(opacity=0);
opacity: 0;
top:0;
left:0;
bottom:0;
right:0;
margin:auto;
}
DEMO HERE

How to get infinite scroll to work?

I'm trying to get this infinite load script to work in my project.
Here's my HTML:
<!-- Contents -->
<div id="page-container">
<div id="scroller">
<div id="page_1" class="pagina"></div>
<div id="page_2" class="pagina"></div>
<div id="page_3" class="pagina"></div>
<div id="page_4" class="pagina"></div>
<div id="page_5" class="pagina"></div>
<div id="page_6" class="pagina"></div>
</div>
</div>
<div id="pages-to-load">
<div id="page_7" class="pagina"></div>
...
<div id="page_25" class="pagina"></div>
</div>
And here's the script:
function scrollalert(){
var pages = document.getElementById("scroller").getElementsByTagName("div");
var currentPageId = pages[pages.length - 1];
//console.log("currentPageId is: "+currentPageId);
var scrollbox = document.querySelector('#page-container');
var scrolltop = $(window).scrollTop();
var scrollheight = scrollbox.scrollHeight;
var windowheight = $(window).height();
var scrolloffset=20;
console.log(scrolltop);
console.log(scrollheight);
console.log(windowheight);
console.log(scrollheight-(windowheight+scrolloffset));
if(scrolltop>=(scrollheight-(windowheight+scrolloffset))) {
//fetch new items
console.log("loading more pages");
(function() {
alert('test');
var i;
var pagesToLoad = $("#pages-to-load > div").size();
for (i = 0; i < pagesToLoad; i++) {
console.log(pagesToLoad[i].id);
$.get(pagesToLoad[i].id, function(newitems){
alert('get new page');
$('#scroller').append(newitems);
updatestatus();
})
};
})();
};
}
Whatever I try, I can't seem to load and append my new pages. Also when scrolling down, my scrollTop and scrollHeight don't change. I'm sure I'm missing something obvious here. Also my pages-to-load is undefined?
Here is one infinite-scroll script of mine using JQuery which works:
Html:
<html>
<head>
<title>Scroll Troll Page</title>
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
<body>
<div id="scrollbox">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
</div>
</body>
<script type="text/javascript">
$(window).scroll(function () {
//- 10 = desired pixel distance from the bottom of the page while scrolling)
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
var box = $("#scrollbox");
//Just append some content here
box.html(box.html() + "<br /><br /><br /><br /><br /><br /><br />");
}
});
</script>
in Line:
box.html(box.html + "Place content to expand here");
You can add the content that should be added to your container when reaching the bottom of the page while scrolling.
Working jsFiddle:
http://jsfiddle.net/MdrJ4/3/
I think we should rely on intersectionObserver instead of the onScroll event. I have put together an article on medium here explaining the performance gains of the two approaches
you only need vanilla js
i have a problem for using endless scrolling, so i wrote a library and solved my problem. i think this library may help you for this problem.
use this library as easy way to implement infinite scrolling :
https://github.com/hamedtaheri32/infinite-scrolling
example :
<script>
$(document).ready(function(){
$(document).infiniteJscroll({
offset:0,
topOfPage:function(){
console.log('Scrolled to Page Top');
},
bottomOfPage:function(){
console.log('Scrolled to Page Bottom');
addContent();
},
pageInit:function(){
console.log('Initialize page');
addContent();
}
});
});
//This method used for simulate loading data from server. replace it with AJAX loading method.
function addContent() {
var c = '';
for (var i = 0; i < 10; i++) {
c += '<a class="box"></a>';
}
$("#post").append(c);
}
</script>
features :
detect page top
detect page bottom
can use offset for detect page bottom
have page initialize method
ability for mix with AJAX loading page
can use below script
window.onscroll = function (ev) {
let scrollHeight = Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
let currentScrollHeight = window.innerHeight + window.scrollY;
if ((scrollHeight - currentScrollHeight) < 200) {
// your statement
}
};
full example in jsfiddle
This is what I did: (Please correct me if I'm wrong)
$(document).ready(() => {
var page = 1;
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
page++;
if (page == 2) {
$('#div2').removeClass('hide');
}
if (page == 3) {
$('#div3').removeClass('hide');
}
if (page == 4) {
$('#div4').removeClass('hide');
page = 1;
}
}
});
});
.page {
width: 100%;
background-color: black;
color: white;
height: 100vh;
border-top: 1px solid white;
}
.hide {
display: none;
}
body {
margin: 0px;
padding: 0px;
}
<!DOCTYPE html>
<html>
<head>
<title>Infinite Scroll</title>
<link href='css/bootstrap.css' ref='stylesheet'>
</head>
<body>
<div id='div' class='page'>
<h1>Page 1</h1>
</div>
<div id='div2' class="page hide">
<h1>Page 2</h1>
</div>
<div id='div3' class="page hide">
<h1>Page 3</h1>
</div>
<div id='div4' class="page hide">
<h1>Page 4</h1>
</div>
<script src='js/jquery.min.js'></script>
<script src='js/popper.min.js'></script>
<script src='js/bootstrap.min.js'></script>
<script src='js/myjquery.js'></script>
</body>
</html>
// check if scrolling near to bootom of page , load more photos
window.addEventListener('scroll',()=>{
if(window.innerHeight+window.scrollY>=document.body.offsetHeight-100){
//your logic or function
}
});

Categories