How to detect if the user has scroll 100px from current position - javascript

I have a one-page website where I am adding a class while the user clicks on nav. However, if the user has scroll 100px from the current location the class need to remove.
DEMO gh pages link
//working fine
var scrollvalue = 0;
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
scrollvalue = $(window).scrollTop();
$(".copyright").addClass("activecopy");
});
//not working fine
$(window).scroll(function() {
if($(window).scrollTop() > 100) {
$('.copyright').removeClass('activecopy');
}
});
Note: I have already read stackoverflow post such as post1 and post2

It's a little hard to figure out what exactly the problem is as you have no shared the corresponding HTML markup. Try the following and let me know if it helps.
var scrollvalue = 0;
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function () {
scrollvalue = $(window).scrollTop();
$(".copyright").addClass("activecopy");
});
$(window).scroll(function () {
if (($(window).scrollTop() - scrollvalue) > 100) {
$('.copyright').removeClass('activecopy');
}
});
EDIT:
As I said, it's hard to see what's happening because you haven't shared markup. Here is a sample. Hope it helps.
EDIT 2:
To make this generic, you can wrap your code which registers for click listeners and scroll listeners in a function which accepts which elements to operate on as arguments. Sample Below.
function registerScrollTrigger(anchor, target) {
var $a = $(anchor);
var $t = $(target);
$a.click(function() {
//Get scroll position at the time of the click
var currentScroll = $(window).scrollTop();
function handleScroll() {
// Demo code to show current scroll on the screen
$t.html('Current Scroll: ' + ($(window).scrollTop() - currentScroll));
// Check if the user has scrolled 100px since clicking the tag
if (($(window).scrollTop() - currentScroll) > 100) {
// Remove active class from element
$t.removeClass('active');
// Demo code ti indicate that the scroll to 100px is complete
$t.html('Complete');
// Stop listening for scroll events [Optional but recommmended]
$(window).off('scroll', handleScroll);
}
}
// Add active class to element [Make it blue]
$t.addClass('active');
// Listen for scroll event and check if 100px has passed
$(window).scroll(handleScroll);
});
}
registerScrollTrigger('#a1', '#scroll1');
registerScrollTrigger('#a2', '#scroll2');
div.scroll {
margin-top: 50px;
}
div.scroll.active {
background: blue;
color: white;
}
div#pad {
height: 1000px;
}
h4 {
margin-bottom: 500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h4>Scroll Down For the Button</h4>
<a id="a1" class="js-scroll">Click Me </a>
<div id="scroll1" class="scroll">
Start scrolling after clicking the above button
</div>
<h4>Scroll Down For Another Button</h4>
<a id="a2" class="js-scroll">Click Me Too</a>
<div id="scroll2" class="scroll">
Start scrolling after clicking the above button
</div>
<div id="pad"></div>
Note:
You can also do something similar by setting a data-target attribute on the anchor which can be used to determine which item to add the class to and remove the class from instead of passing both items as a parameter

$(window).scroll(function() {
var height = $(window).scrollTop();
if (height > 100) {
$(".copyright").addClass("activecopy");
} else {
$('.copyright').removeClass('activecopy');
}
});
I am using this for showing my gototop button in bottom. Hope this will works for you.....

Related

I am currently removing jquery from my code and I am not able to convert this Jquery to Javascript

I am currently removing the Jquery from my website but i am not able to successfully convert it to JavaScript. I know its probably very stupid but i am still a beginner. Could anyone help?
$(document).scroll(function(){
$('.navbar').toggleClass('scrolled', $(this).
scrollTop() > $('.navbar').height());
});
You can try something like this:
window.onscroll = function() {
var nav = document.querySelector('.navbar');
var isScrolled = document.body.scrollTop > nav.offsetHeight || document.documentElement.scrollTop > nav.offsetHeight;
nav.classList.toggle("scrolled", isScrolled);
};
.container {
height: 2000px;
}
.nav-link {
display: block;
color: red;
}
.scrolled .nav-link {
color: blue;
}
<div class="container">
<div class="navbar">
Navbar
<a class="nav-link">aaa</a>
<a class="nav-link">bbb</a>
<a class="nav-link">ccc</a>
</div>
</div>
We're subscribing to the window's onscroll event. We grab a reference to your navbar element using document.querySelector(). Then we use that elements height (offsetHeight) to determine if it should have the .scrolled class. Finally, we use the toggle() method on the navbar element's classList property.
UPDATE based on comments:
If you must have many separate functions to handle the same event, you're better off using the window.addEventListener() syntax.
window.addEventListener('scroll', function() {
var nav = document.querySelector('.navbar');
var isScrolled = document.body.scrollTop > nav.offsetHeight || document.documentElement.scrollTop > nav.offsetHeight;
nav.classList.toggle("scrolled", isScrolled);
});
window.addEventListener('scroll', function() {
// ...
console.log('scroll b');
});
window.addEventListener('scroll', function() {
// ...
console.log('scroll c');
});
.container {
height: 2000px;
}
<div class="container">
<div class="navbar">Navbar</div>
</div>
The first line can be replaced it with an "addEventListener" like this
window.addEventListener('scroll', function (e) {
});
to replace the toggle function you can use the "classList" property. Save the element in a new variable and then "element.classList.remove('class')" or "element.classList.add('class')
var navbar = document.getElementById("navbar");
navbar.classList.remove("scrolled");
navbar.classList.add("scrolled");
Use this.scrollY to get the window ScrollY position, and element.clientHeight to get the height of the element including paddings (there are others methods to get the height that can fit more to your needs)
if (this.scrollY > navbar.clientHeight) {}
The end result will be something like this
window.addEventListener('scroll', function (e) {
var navbar = document.getElementById("navbar");
navbar.classList.remove("scrolled");
if (this.scrollY > navbar.clientHeight) {
navbar.classList.add("scrolled");
}
});

How can i trigger a css class when a reach to a specific div with scroll

i am new to Javascript and i would like your help.
I have a code and when you scroll from the top of a page changes css of a class and zooms the images.
What i would like to do is, to put a class in a div ( lets say .start) and when i reach to that class then to start zoom the image.
$(window).scroll(function () {
var scroll = $(window).scrollTop();
$(".zoom").css({
backgroundSize: (100 + scroll / 20) + "%"
});
});
Check this: getBoundingClientRect()
HTML
<div class="wrap">
<div class="content">A</div>
<div class="content">B</div>
<div id="start" class="content">C</div>
<div class="zoom"><!-- Image --></div>
</div>
JS
$(window).scroll(function () {
var target = $('#start')[0].getBoundingClientRect(); // id="start" Element
// Start zoom at #start element's position
if (target.top - target.height <= 0) {
$(".zoom").css({
backgroundSize: (100 + (target.height - target.top) / 20) + "%"
});
}
});
getBoundingClientRect() is returns the size of an element and its position relative to the viewport.
You can check the target Element's position and trigger it.
Demo: https://jsfiddle.net/ghlee/uecb26ft
I guess this question is similar to your problem?
You will need to add your zoom class to the element via .addClass("zoom"); when it is in the viewport.
Well not that exactly.
i have this
$(window).scroll(function () {
$('#currentContent').bind('inview', monitor);
function monitor(event, visible)
{
if(visible)
{
$(window).scroll(function () {
var scroll = $(window).scrollTop();
$(".zoom").css({
backgroundSize: (100 + scroll / 20) + "%"
});
});
}
else
{
// element has gone out of the viewport
}
}
});
The "problem" is var scroll = $(window).scrollTop();
I want the scroll variable to start not from TOP but from the div where i have add a class.
I have tried this var scroll = $('.currentContent').offset().top;
But nothing happens
To determine if an element with the desired class is in the viewport (i.e., been scrolled to), you could calculate the offset of the .start element and compare it with the current scroll value on scroll.
If the element is in the viewport, you could then zoom the image. The below snippet will increase the image size when you reach it. Just zoom past the height of the red area. If you scroll back up, it should get smaller. You may want a different effect, but the same idea applies.
Also, see my comments in the inViewport function.
$(window).scroll(function() {
if (inViewport($(".start"))) {
$(".start").css("height", "200px").css("width", "200px");
} else {
$(".start").css("height", "50px").css("width", "50px");
}
});
function inViewport(element) {
// added extra height so you can see the element change back to smaller size
// you could remove this value if you just want the element to change size when out of the viewport
const extra = 50;
var elementTop = element.offset().top + extra;
var elementBottom = elementTop + element.outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
#placeholder {
height: 300px;
background-color: red;
}
.start {
height: 50px;
width: 50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="placeholder"></div>
<img class="start" src="https://homepages.cae.wisc.edu/~ece533/images/airplane.png" />
This is what Intersection Observer was made to do. With this you can watch elements and react when they come into view or intersect with each other.
First you set the options for the IO:
let options = {
rootMargin: '0px',
threshold: 1.0
}
let observer = new IntersectionObserver(callback, options);
If you leave out the root option it wall default to your browser window, so once an element that you watch comes into viewport, the callback function gets triggered.
Then you specify which elements you want to observe:
let target = document.querySelector('.zoom');
observer.observe(target);
Here we now watch every element with the class zoom.
Last step is to define the callback function:
let callback = (entries, observer) => {
entries.forEach(entry => {
// Each entry describes an intersection change for one observed
// target element:
// like: $(element).addClass('zoom');
});
};
You can unobserve an element if you don't need it anymore, for example if you only want to play the zoom animation only once when it comes into view.
Also check out this example on how to change bg-color depending on how much of an element is visible on screen.
Edit: Maybe this example is more fitting (see comments) because it actually adds a class when user scrolls to the element.
Last point, you can use this polyfill from w3c to support older browsers.
Well, you seem to be on the right path. You probably in addition need to pay attention to the background-size property. Instead of the JavaScript strongly named backgroundSize for the css background-size property, accessed through the style object of an element like this; currentElement.style.backgroundSize, you might want to do this; "background-size": (100 + scroll / 20) + "%. Here's a working example that builds upon your existing code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>My page</title>
</head>
<body>
<h1 id="start">My Zoom Heading</h1>
<p class="zoom">My zoom area</p>
<script>
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var zoomStart = $("#start").offset().top;
if (scroll >= zoomStart) {
$(".zoom").css({
"background-size": (100 + scroll / 10) + "%"
});
}
});
</script>
<style>
#start {
margin-top: 60px;
}
.zoom {
margin-top: 10px;
margin-bottom: 300px;
width: 300px;
height: 300px;
background: url('{some-image-url-here}') no-repeat;
}
</style>
</body>
</html>

Track when user scrolls past div that is in an array

Is there a way to set an array of html elements. say Section_1, Section_2, and Section_3 are within said array. While the user scrolls down the page, and only on down-scroll, is it possible to check whether the user scrolls by sections that are specified in that array? Kinda like...
var readerLocation = 150;
var content = ['block_1', 'block_2', 'block_3'];
bottom = $(window).height() + $(window).scrollTop();
height = $(document).height();
// If user starts to scroll send an event
if (bottom > readerLocation) {
console.log('started reading');
var i = 0;
for (block in content) {
console.log(content[i]);
//check if scrolled past element in array here()
i++;
}
}
What you can do is set a $(window).scroll() event.
For each element in your array, you want to find its offset within the page, and compare it to your current $(window).scrollTop(). Whenever it passes say the offset().top of Section_1, then you know that it's in section 1 and has not yet reached section 2.
Here is a code sample that will take you close to where you want to be:
A few things to keep in mind:
Run your code by specifying your conditions within the array foreach loop.
Make sure to keep track of variables rather than applying code on the fly.
Since you are using jQuery, make good use of $(window).scroll to keep track of your scroll events.
$(document).ready(function(){
var lastScrollTop = 0,
block = ['block_2', 'block_5', 'block_7'];
$(window).scroll(function(event){
var st = $(this).scrollTop(),
block_2_offset = $('#' + block[0]).offset().top;
if (st > lastScrollTop){
// downscroll
block.forEach(function(block, i) {
// check if we passed through on scroll down, then do something, modify the condition for a more specialized response
if(st >= $('#' + content[i]).offset().top){
// do something
}
});
}
lastScrollTop = st;
});
});
div {
padding-bottom: 500px;
text-align: center;
}
div:nth-child(3) {
background-color: blue;
}
div:nth-child(6) {
background-color: yellow;
}
div:nth-child(8) {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block_1">
block 1
</div>
<div id="block_2">
block 2
</div>
<div id="block_3">
block 3
</div>
<div id="block_4">
block 4
</div>
<div id="block_5">
block 5
</div>
<div id="block_6">
block 6
</div>
<div id="block_7">
block 7
</div>
<div id="block_8">
block 8
</div>
<div id="block_9">
block 9
</div>

Trigger event when user scroll to specific element - with jQuery

I have an h1 that is far down a page..
<h1 id="scroll-to">TRIGGER EVENT WHEN SCROLLED TO.</h1>
and I want to trigger an alert when the user scrolls to the h1, or has it in it's browser's view.
$('#scroll-to').scroll(function() {
alert('you have scrolled to the h1!');
});
how do I do this?
You can calculate the offset of the element and then compare that with the scroll value like:
$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > (hT+hH-wH)){
console.log('H1 on the view!');
}
});
Check this Demo Fiddle
Updated Demo Fiddle no alert -- instead FadeIn() the element
Updated code to check if the element is inside the viewport or not. Thus this works whether you are scrolling up or down adding some rules to the if statement:
if (wS > (hT+hH-wH) && (hT > wS) && (wS+wH > hT+hH)){
//Do something
}
Demo Fiddle
Combining this question with the best answer from jQuery trigger action when a user scrolls past a certain part of the page
var element_position = $('#scroll-to').offset().top;
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var scroll_pos_test = element_position;
if(y_scroll_pos > scroll_pos_test) {
//do stuff
}
});
UPDATE
I've improved the code so that it will trigger when the element is half way up the screen rather than at the very top. It will also trigger the code if the user hits the bottom of the screen and the function hasn't fired yet.
var element_position = $('#scroll-to').offset().top;
var screen_height = $(window).height();
var activation_offset = 0.5;//determines how far up the the page the element needs to be before triggering the function
var activation_point = element_position - (screen_height * activation_offset);
var max_scroll_height = $('body').height() - screen_height - 5;//-5 for a little bit of buffer
//Does something when user scrolls to it OR
//Does it when user has reached the bottom of the page and hasn't triggered the function yet
$(window).on('scroll', function() {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if(element_in_view || has_reached_bottom_of_page) {
//Do something
}
});
I think your best bet would be to leverage an existing library that does that very thing:
http://imakewebthings.com/waypoints/
You can add listeners to your elements that will fire off when your element hits the top of the viewport:
$('#scroll-to').waypoint(function() {
alert('you have scrolled to the h1!');
});
For an amazing demo of it in use:
http://tympanus.net/codrops/2013/07/16/on-scroll-header-effects/
Inview library triggered event and works well with jquery 1.8 and higher!
https://github.com/protonet/jquery.inview
$('div').on('inview', function (event, visible) {
if (visible == true) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});
Read this https://remysharp.com/2009/01/26/element-in-view-event-plugin
Fire scroll only once after a successful scroll
Note: By successful scroll I mean when the user has scrolled to the desired
element or in other words when the desired element is in view
The accepted answer worked 90% for me so I had to tweak it a little to actually fire only once.
$(window).on('scroll',function() {
var hT = $('#comment-box-section').offset().top,
hH = $('#comment-box-section').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
if (wS > ((hT+hH-wH)-500)){
console.log('comment box section arrived! eh');
// This detaches the scroll so doStuff() won't run more than once
$(window).off('scroll');
doStuff();
}
});
You could use this for all devices,
$(document).on('scroll', function() {
if( $(this).scrollTop() >= $('#target_element').position().top ){
do_something();
}
});
Intersection Observer can be the best thing IMO, without any external library it does a really good job.
const options = {
root: null,
threshold: 0.25, // 0 - 1 this work as a trigger.
rootMargin: '150px'
};
const target = document.querySelector('h1#scroll-to');
const observer = new IntersectionObserver(
entries => { // each entry checks if the element is the view or not and if yes trigger the function accordingly
entries.forEach(() => {
alert('you have scrolled to the h1!')
});
}, options);
observer.observe(target);
You can use jQuery plugin with the inview event like this :
jQuery('.your-class-here').one('inview', function (event, visible) {
if (visible == true) {
//Enjoy !
}
});
Link : https://remysharp.com/2009/01/26/element-in-view-event-plugin
This should be what you need.
Javascript:
$(window).scroll(function() {
var hT = $('#circle').offset().top,
hH = $('#circle').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 900,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
}); {
$('.count').removeClass('count').addClass('counted');
};
}
});
CSS:
#circle
{
width: 100px;
height: 100px;
background: blue;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
float:left;
margin:5px;
}
.count, .counted
{
line-height: 100px;
color:white;
margin-left:30px;
font-size:25px;
}
#talkbubble {
width: 120px;
height: 80px;
background: green;
position: relative;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px;
float:left;
margin:20px;
}
#talkbubble:before {
content:"";
position: absolute;
right: 100%;
top: 15px;
width: 0;
height: 0;
border-top: 13px solid transparent;
border-right: 20px solid green;
border-bottom: 13px solid transparent;
}
HTML:
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>
Check this bootply:
http://www.bootply.com/atin_agarwal2/cJBywxX5Qp
If you are looking for a javascript version. You can call this method on scroll event listener.
showScrollTop = () =>{
const currentScrollPosition = window.pageYOffset;
let elementID = 'service-selector'
const elementOffsetTop = document.getElementById(elementID).offsetTop
if ( currentScrollPosition > elementOffsetTop){
// place your logic here
} else {
// place your logic here
}
}
window.addEventListener('scroll', showScrollTop)
If you are doing a lot of functionality based on scroll position, Scroll magic (http://scrollmagic.io/) is built entirely for this purpose.
It makes it easy to trigger JS based on when the user reaches certain elements when scrolling. It also integrates with the GSAP animation engine (https://greensock.com/) which is great for parallax scrolling websites
Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.
Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.
function elementInView(el) {
// The vertical distance between the top of the page and the top of the element.
var elementOffset = $(el).offset().top;
// The height of the element, including padding and borders.
var elementOuterHeight = $(el).outerHeight();
// Height of the window without margins, padding, borders.
var windowHeight = $(window).height();
// The vertical distance between the top of the page and the top of the viewport.
var scrollOffset = $(this).scrollTop();
if (elementOuterHeight < windowHeight) {
// Element is smaller than viewport.
if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
// Element is completely inside viewport, reveal the element!
return true;
}
} else {
// Element is larger than the viewport, handle visibility differently.
// Consider it visible as soon as it's top half has filled the viewport.
if (scrollOffset > elementOffset) {
// The top of the viewport has touched the top of the element, reveal the element!
return true;
}
}
return false;
}
I use the same code doing that all the time, so added a simple jquery plugin doing it.
480 bytes long, and fast. Only bound elements analyzed in runtime.
https://www.npmjs.com/package/jquery-on-scrolled-to
It will be
$('#scroll-to').onScrolledTo(0, function() {
alert('you have scrolled to the h1!');
});
or use 0.5 instead of 0 if need to alert when half of the h1 shown.
Quick and fast implementation,
let triggered = false;
$(window).on('scroll',function() {
if (window.scrollY > ($('#scrollTo').offset().top+$('#scrollTo').outerHeight()-window.innerHeight) & !triggered){
console.log('triggered here on scroll..');
triggered = true;
}
});
using global variable triggered = false makes it just to happen once, otherwise, every time crossing past the element, this action is triggered.

Scroll event background change

I am trying to add a scroll event which will change the background of a div which also acts as the window background (it has 100% width and height). This is as far as I get. I am not so good at jquery. I have seen tutorials with click event listeners. but applying the same concept , like, returning scroll event as false, gets me nowhere. also I saw a tutorial on SO where the person suggest use of array. but I get pretty confused using arrays (mostly due to syntax).
I know about plugins like waypoints.js and skrollr.js which can be used but I need to change around 50-60 (for the illusion of a video being played when scrolled) ... but it wont be feasible.
here is the code im using:-
*
{
border: 2px solid black;
}
#frame
{
background: url('1.jpg') no-repeat;
height: 1000px;
width: 100%;
}
</style>
<script>
$(function(){
for ( i=0; i = $.scrolltop; i++)
{
$("#frame").attr('src', ''+i+'.jpg');
}
});
</script>
<body>
<div id="frame"></div>
</body>
Inside your for loop, you are setting the src attribute of #frame but it is a div not an img.
So, instead of this:
$("#frame").attr('src', ''+i+'.jpg');
Try this:
$("#frame").css('background-image', 'url(' + i + '.jpg)');
To bind a scroll event to a target element with jQuery:
$('#target').scroll(function() {
//do stuff here
});
To bind a scroll event to the window with jQuery:
$(window).scroll(function () {
//do stuff here
});
Here is the documentation for jQuery .scroll().
UPDATE:
If I understand right, here is a working demo on jsFiddle of what you want to achieve.
CSS:
html, body {
min-height: 1200px; /* for testing the scroll bar */
}
div#frame {
display: block;
position: fixed; /* Set this to fixed to lock that element on the position */
width: 300px;
height: 300px;
z-index: -1; /* Keep the bg frame at the bottom of other elements. */
}
Javascript:
$(document).ready(function() {
switchImage();
});
$(window).scroll(function () {
switchImage();
});
//using images from dummyimages.com for demonstration (300px by 300px)
var images = ["http://dummyimage.com/300x300/000000/fff",
"http://dummyimage.com/300x300/ffcc00/000",
"http://dummyimage.com/300x300/ff0000/000",
"http://dummyimage.com/300x300/ff00cc/000",
"http://dummyimage.com/300x300/ccff00/000"
];
//Gets a valid index from the image array using the scroll-y value as a factor.
function switchImage()
{
var sTop = $(window).scrollTop();
var index = sTop > 0 ? $(document).height() / sTop : 0;
index = Math.round(index) % images.length;
//console.log(index);
$("#frame").css('background-image', 'url(' + images[index] + ')');
}
HTML:
<div id="frame"></div>
Further Suggestions:
I suggest you change the background-image of the body, instead of the div. But, if you have to use a div for this; then you better add a resize event-istener to the window and set/update the height of that div with every resize. The reason is; height:100% does not work as expected in any browser.
I've done this before myself and if I were you I wouldn't use the image as a background, instead use a normal "img" tag prepend it to the top of your page use some css to ensure it stays in the back under all of the other elements. This way you could manipulate the size of the image to fit screen width better. I ran into a lot of issues trying to get the background to size correctly.
Html markup:
<body>
<img src="1.jpg" id="img" />
</body>
Script code:
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200) {
// function goes here
$('img').attr('src', ++count +'.jpg');
}
});
});
I'm not totally sure if this is what you're trying to do but basically, when the window is scrolled, you assign the value of the distance to the top of the page, then you can run an if statement to see if you are a certain point. After that just simply change run the function you would like to run.
If you want to supply a range you want the image to change from do something like this, so what will happen is this will allow you to run a function only between the specificied range between 200 and 400 which is the distance from the top of the page.
$(function(){
var topPage = 0, count = 0;
$(window).scroll( function() {
topPage = $(document).scrollTop();
if(topPage > 200 && topPage < 400) {
// function goes here
$('#img').attr('src', ++count +'.jpg');
}
});
});

Categories

Resources