How do I make a fixed positioned object move from the top of my browser window to the bottom of the page when I browse my website?

I have a website that is 6 times the size of my browser window. I want a fixed positioned image to move from the top of the browser window to the bottom when I view the top of my website at the bottom.

Id give you some example code, but I am completely stuck with this and don't even know where to start.

I'm just looking for a very simple example. I'm limited to html5, css and jquery.

+3


source to share


4 answers


check it:

http://codepen.io/anon/pen/zolLe



$( ".scroll__inner" ).click( function(){
    console.log("this1");
    window.scrollBy(0,600); 
}); 

      

In this I added one per click event to scroll down, and all the others are the same as @ckuijjer's answer. For scrolling down, I used function scrolling. You can also scroll down by specifying the scroll height.

+1


source


You need to know how big the document is var documentHeight = $(document).height()

, how big the screen is, var screenHeight = $(window).height()

and how far the user scrolls var scrollAmount = $(window).scrollTop

.

Calculate the maximum amount you can scroll var maxScrollAmount = documentHeight - windowHeight

and use that to determine how much of a page has already been seen (a number between zero and one) var amountSeen = scrollAmount / maxScrollAmount

. If you multiply this by the window size, you know how far top

your image should bevar top = amountSeen * windowHeight



I started with a little jQuery plugin that you can extend, see http://codepen.io/ckuijjer/pen/lGqAs . It does not support document resizing and it is not optimized, but it starts.

+2


source


Regardless of what you are moving, the main thing you need is the scroll position of the browser window as a percentage. This requires a little calculation, since the scroll position is only provided by the browser as the number of pixels above the top of the screen:

// Vanilla Javascript
var scrollPercent = document.body.scrollTop / (document.body.scrollHeight - window.innerHeight);

// JQuery
var scrollPercent = $(window).scrollTop() / ($(document.body).height() - $(window).height());

      

When you have a scroll position in the form of interest, you can use it to set the property top

of your fixed element, to put it in the window scrollPercent * window.height

.

Here's a JSFiddle that demonstrates this.

+1


source


If you want to have an image displayed in all scrolling windows on all windows, put this style in your images tag:

<img id="img1" src="" style="position:fixed; top=0; left=o; width:100%; height:100%; z-index:-10;" />

$(function(){
    $("#img1").css({"height": $(document.height()) + "px", "width": $(document.width()) + "px"});
});

      

0


source







All Articles