Connect a div's width to scrollTop() value with jQuery / javascript - javascript

I'm trying to make a scroll progress bar for a website. Basically, I want the width of a div (with a colored background) to be associated with how far the user has scrolled down.
I'm pretty new to jQuery--it's only my second project. Any ideas on how I could get it to work?
Here's my HTML:
<div class="scroll-progress"></div>
Here's the CSS:
.scroll-progress {
width:10px; height:10px;
background-color:green;
position:fixed;
top:0em;
left:0em;
}
and the jQuery I took a hack at:
$(document).ready(function(){
$(window).scroll(function(){
var docHeight = $(document).height();
var scrollDepth = $(window).scrollTop();
var scrollPercent = parseFloat(scrollDepth / docHeight) * 100;
$(".scroll-progress").css(width,scrollPercent);
});
});

I developed your project a little bit, check this out:
(multiplicator is 103, and not 100, because of difference that the scrollbar height is causing itself)
http://jsfiddle.net/tdBfD/5/
$(document).ready(function(){
$(window).scroll(function(){
var docHeight = $(document).height();
var ScrollTop = $(window).scrollTop();
var NewWidth = (ScrollTop / docHeight) * 103
$(".scroll-progress").width(NewWidth);
});
});

Related

Jquery transition Opacity based on var value

I am trying to animate an opacity value from 0 to 1, based on the scroll position within the viewport height. The code below sets variables for windowHeight and scrollTop, which can be combined to calculate percentageScrolled (0–100) of the viewport height. Based on this I am able to switch CSS values at set points, but instead I want to gradually change the opacity from 0–100 of percentageScrolled.
How can I adjust the code below to transition/animate the opacity?
Thanks.
$(window).on('scroll', function(){
// Vars
var windowHeight = $(window).height();
var scrollTop = $(this).scrollTop();
var percentageScrolled = (scrollTop*100)/windowHeight;
if( percentageScrolled < 100 ) {
$('.colour-overlay').css('opacity', '1');
} else {
$('.colour-overlay').css('opacity', '0');
}
});
You can remove the if and set the opacity to the percentage divided by 100
$(window).on('scroll', function() {
// Vars
var windowHeight = $(window).height();
var scrollTop = $(this).scrollTop();
$('.colour-overlay').css('opacity', scrollTop / windowHeight);
});
.colour-overlay {
display: block;
width: 20px;
height: 1200px;
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colour-overlay"></div>
$(‘.colour-overlay’).css(opacity, percentageScrolled / 100);
Instead of if else statement.
Also as a general advice try to avoid using var, use const or let instead and if your project doesnt depend on jquery try to avoid it too.
const overlays = document.querySelectorAll(‘.colour-overlay’);
window.addEventListener('scroll', () => {
const windowHeight = window.offsetHeight;
const scrollTop = window.scrollTop;
const percentageScrolled = (scrollTop * 100) / windowHeight;
for (const overlay of overlays) {
overlay.style.opacity = percentageScrolled / 100;
}
});
This would be the pure js solution.
Dont know if i understood you right, but a wrote an example have a look.
$(document).on('scroll', function(){
// Vars
// use body instead of window, body will return the right height where window will return the view size
var windowHeight = $("body").height();
var scrollTop = $(this).scrollTop();
var percentageScrolled = Math.abs((((scrollTop / windowHeight) * 100) / 100 ));
$('.colour-overlay').css('opacity', percentageScrolled);
});
.colour-overlay{
background:red;
height:1000px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="colour-overlay"></div>

How to stop scroll when dynamic div ends

I want to stop scroll after a dynamic div reaches its end. This div will be holding dynamic content so the size never stays the same. I know how to lock in position when scroll hits a pre-defined height, but not sure how to do it when the hight is constantly changing. here's what i'm using for my standard locking scroll when it hits specific point:
var profile_rc = $("#profile-rc");
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 285) {
profile_rc.addClass("p-right-column");
} else {
profile_rc.removeClass("p-right-column");
}
});
Looks like you are using jQuery, the following 2 examples might help.
Detecting dynamic height of screen
<script>
$(function(){
var windowHeight = $(window).height();
$(window).resize(function() {
windowHeight = $(window).height();
console.log(windowHeight);
});
});
<script>
Detecting dynamic height of a div
<script>
$(function(){
var divHeight = $('#your-div-id').css("height");
$( window ).on("resize", function() {
divHeight = $('#your-div-id').css("height");
console.log(divHeight);
});
});
</script>
I got it to work doing this:
$(window).scroll(function() {
var divHeight = $('#farleft-cont').outerheight(true);
var ycbc = $('#target-div');
var scroll = $(window).scrollTop();
if (scroll >= divHeight) {
ycbc.addClass("target-div-fixed");
} else {
ycbc.removeClass("target-div-fixed");
}
});

Progressively adding opacity while scrolling

I am struggling with figuring out how to modify some existing code I have to replicate a feature I saw on a site. If you go to this site: , when you scroll down you will see the image gains opacity. My fiddle somewhat does this, but I cannot figure out how to apply a darker opacity and have the opacity progressively be added rather than all at once.
I know the level of opacity is being changed via the javascript, I am just not aware how to modify it to get the result I am after.
var scrollPosition = $(this).scrollTop();
var docHeight = $(document).height();
var diff = docHeight - scrollPosition;
console.log(scrollPosition);
$('#demolition1').css({'opacity':diff/docHeight});
Fiddle
<div id="home-main-img">
<img src="http:optimumwebdesigns.com/images/demolition1.jpg" alt="Demolition and Wrecking" id="demolition1">
</div>
<div class="height">
</div>
#home-main-img img{
width: 100%;
height: auto;
margin: 0;
display: block;
}
#home-main-img {
background: #000;
}
.height {
height:500px;
}
$(document).scroll(function(e){
var scrollPosition = $(this).scrollTop();
var docHeight = $(document).height();
var diff = docHeight - scrollPosition;
console.log(scrollPosition);
$('#demolition1').css({'opacity':diff/docHeight});
});
I think your mistake is setting diff against the doc height rather than the height of the item you want to fade out.
Your JS should be something like:
var $item = $('#demolition1');
$(document).scroll(function(e) {
var $this = $(this),
scrollPosition = $this.scrollTop(),
itemHeight = $item.height(),
diff = itemHeight - scrollPosition;
console.log(scrollPosition);
$item.css({'opacity': (diff/itemHeight) });
});
Here's a working JS Fiddle: https://jsfiddle.net/s6ta6bdc/
You can use image height, instead of document, to get the correct percentage of opacity
$(document).scroll(function(e){
var scrollPosition = $(this).scrollTop();
var imgHeight = $('#demolition1').height();
var diff = imgHeight - scrollPosition;
$('#demolition1').css({'opacity':diff/imgHeight});
});
try fiddle updated

jQuery .scroll not picking up

I'm trying create an alert saying "True" when the user scrolls past the "#topp" element, yet it isn't doing anything, the element is just supposed to be a tiny div at the top of the page.
HTML
<div id="topp"></div>
jQuery
$(window).scroll(function() {
var vpH = $(window).height(),
st = $(window).scrollTop(),
y = $('#topp').offset().top;
if(y > (st + vpH)) alert('true');
});
Why do you need the window height? If you have the top and the scroll to top variables then theirs no need for the height of the window.
$(document).scroll(function()
{
var scrollTop = $(window).scrollTop();
var toppOffset = $('#topp').offset().top;
if(toppOffset > scrollTop)
alert('true');
});​
A clearer representation http://jsfiddle.net/zDpw3/1/

jquery: $(window).scrollTop() but no $(window).scrollBottom()

I want to place an element to the bottom of the page whenever the user scrolls the page. It's like "fixed position" but I can't use "position: fixed" css as many of my clients' browser can't support that.
I noticed jquery can get current viewport's top position, but how can I get the bottom of the scroll viewport?
So I am asking how to know: $(window).scrollBottom()
var scrollBottom = $(window).scrollTop() + $(window).height();
I would say that a scrollBottom as a direct opposite of scrollTop should be:
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
Here is a small ugly test that works for me:
// SCROLLTESTER START //
var showerEl = $('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>')
showerEl.insertAfter('body');
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
var scrollBottom = $(document).height() - $(window).height() - scrollTop;
showerEl.html('scrollTop: ' + scrollTop + '<br>scrollBottom: ' + scrollBottom);
});
// SCROLLTESTER END //
For the future, I've made scrollBottom into a jquery plugin, usable in the same way that scrollTop is (i.e. you can set a number and it will scroll that amount from the bottom of the page and return the number of pixels from the bottom of the page, or, return the number of pixels from the bottom of the page if no number is provided)
$.fn.scrollBottom = function(scroll){
if(typeof scroll === 'number'){
window.scrollTo(0,$(document).height() - $(window).height() - scroll);
return $(document).height() - $(window).height() - scroll;
} else {
return $(document).height() - $(window).height() - $(window).scrollTop();
}
}
//Basic Usage
$(window).scrollBottom(500);
var scrollBottom =
$(document).height() - $(window).height() - $(window).scrollTop();
I think it is better to get bottom scroll.
This will scroll to the very top:
$(window).animate({scrollTop: 0});
This will scroll to the very bottom:
$(window).animate({scrollTop: $(document).height() + $(window).height()});
.. change window to your desired container id or class if necessary (in quotes).
try:
$(window).scrollTop( $('body').height() );
Here is the best option scroll to bottom for table grid, it will be scroll to the last row of the table grid :
$('.add-row-btn').click(function () {
var tempheight = $('#PtsGrid > table').height();
$('#PtsGrid').animate({
scrollTop: tempheight
//scrollTop: $(".scroll-bottom").offset().top
}, 'slow');
});
// Back to bottom button
$(window).scroll(function () {
var scrollBottom = $(this).scrollTop() + $(this).height();
var scrollTop = $(this).scrollTop();
var pageHeight = $('html, body').height();//Fixed
if ($(this).scrollTop() > pageHeight - 700) {
$('.back-to-bottom').fadeOut('slow');
} else {
if ($(this).scrollTop() < 100) {
$('.back-to-bottom').fadeOut('slow');
}
else {
$('.back-to-bottom').fadeIn('slow');
}
}
});
$('.back-to-bottom').click(function () {
var pageHeight = $('html, body').height();//Fixed
$('html, body').animate({ scrollTop: pageHeight }, 1500, 'easeInOutExpo');
return false;
});
var scrolltobottom = document.documentElement.scrollHeight - $(this).outerHeight() - $(this).scrollTop();
For an item in my page :
document.getElementById(elementId).scroll(0,
document.getElementById(elementId).scrollHeight);
function scrollBottum(elementId){
document.getElementById(elementId).scroll(0, document.getElementById(elementId).scrollHeight);
}
<html><div><button onclick="scrollBottum('myCart')">Click me to scroll</button></div>
<div id="myCart" style="height: 50px; overflow-y: scroll;">
<div>1: A First ...</div>
<div>2: B</div>
<div>3: C</div>
<div>4: D</div>
<div>5: E</div>
<div>6: F</div>
<div>7: LAST !!</div>
</div>
</html>
i try that and it work very well
scrollrev(){
let x:any= document.getElementById('chat')
x.scrollTop = -9000;
}
i try that code and it work
// scroll top
scroll(){
let x:any= document.getElementById('chat')
x.scrollTop = 9000;
}
// scroll buttom
scrollrev(){
let x:any= document.getElementById('chat')
x.scrollTop = -9000;
}
This is a quick hack: just assign the scroll value to a very large number. This will ensure that the page is scrolled to the bottom.
Using plain javascript:
document.body.scrollTop = 100000;

Categories