Scroll to bottom of div event (overflow) - javascript

Hi please help me with my fiddle HERE
I have this div
<div id='divdiv' style="height: 200px; overflow:scroll">
<span id='content'>
Scroll down!Scroll down!
Scroll down!Scroll down!
Scroll down!Scroll down!
Scroll down!Scroll down!
Scroll down!Scroll down!
Scroll down!Scroll down!
</span>
<i id="selectedElement">s</i>
</div>
this div has overflow and I have scroll event that trigger when <i id="selectedElement">s</i> is visible in div
//function to check if target element is visible
function isElementVisible(elementToBeChecked)
{
var TopView = $('#divdiv').scrollTop();
var BotView = TopView + $('#divdiv').height();
var TopElement = $(elementToBeChecked).offset().top;
var BotElement = TopElement + $(elementToBeChecked).height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
//scroll event
$('#divdiv').scroll(function () {
isOnView = isElementVisible("#selectedElement");
if(isOnView){
$('#content').append('<br>a<br>a<br>a<br>a<br>a<br>a<br>a');
}else{ // If not visible
}
});
if the <i id="selectedElement">s</i> is visible i added some value '<br>a<br>a<br>a<br>a<br>a<br>a<br>a' just to test if i reach the bottom but I can't make it work.
it should function as
when the target element is visible i will load some content then user will scroll again to bottom and when the target element is "again" visible i will load some more content again

I have updated the fiddle here.
This appends a random number to the 'content' div as soon as it reaches the bottom.
function appendContent()
{
if ($('#divdiv')[0].scrollHeight <= $('#divdiv')[0].scrollTop + $('#divdiv').height() ) {
return true;
}
else
return false;
}
$('#divdiv').scroll(function () {
if(appendContent()){
$('#content').append('<br>' + Math.random());
}else{ // If not visible
}
});

Check this Demo Fiddle
Use this
$('#divdiv').scrollTop($('#divdiv').prop("scrollHeight"));
OR
$('#divdiv').scrollTop($('#divdiv')[0].scrollHeight);
scrollTop() scrolls the div to the bottom.
prop("scrollHeight") gives your the actual height, and not default display height - height().

Related

How to detect scroll inside “body” and get rid of scrollTop() returns 0

I have set a Scroll event to trigger fade out or fade in effect for "$("#btn")" , but I am not even able to detect the scroll event when its is scrolled, when check the value of scroll it return as 0, due to which it is not reflecting anything.
Issue: Not able to detect any kind of scroll event and not able to get scrolled values
Here is the which I tried
https://jsfiddle.net/evwrs0jq/1/
$(document).ready(function(){
$("body").on("scroll", function(){
alert();
var currentScroll = $(this).scrollTop()
var BtnAction = $("#btn");
if (currentScroll > offset) {
BtnAction.fadeOut(duration);
} else {
BtnAction.fadeIn(duration);
}
offset = currentScroll;
});
});
I guess you want this: https://jsfiddle.net/evwrs0jq/2/
<div id="test" ...
$("#test").on("scroll", function(){ ...
The body itself doesn't scroll here, it is the div that scrolls. That's why your alert didn't show up.

How do I code JQuery so that when I scroll to a certain element, Nav bar appears at top, when I scroll back up past that element, nav bar disappears

I have a div called #menu which I want to display when I scroll past the element #section3, if I scroll up past that element again, I want #menu to disappear
How would I code this?
Maybe something like this?
scrolled = "no"
$(window).scroll(function(){
scr = $("body").scrollTop();
if (scr > 100 && scrolled == "no"){
$("#menu").css({"display:block"})
displayed = "yes"
}
if (displayed == "yes" && scrolled = "yes"){
$("#menu").css({"display:none"})
}
});
The above assumes that #section3 is 100 pixels down the page. If you do not know where its going to be on the page then you could use the method outlined here:
Trigger event when user scroll to specific element - with jQuery
With jQuery you can get the scroll position with $("body").scrollTop();.
Expanding on what #Ned Hulton said, I recommend comparing the scroll position to the top of a "container element" (or 'row') in your page like this:
if ($('body').scrollTop() > $('#someRow').offset().top){
//do something
}
That way you can account for your container appearing at a variable distance down the page (which will come in handy for mobile browsing or cases where your text wraps to additional lines)
I just whipped this up in jsfiddle
https://jsfiddle.net/rb56j0yu/
it uses jQuery, and checks the scroll position against the target div. Css sets the menu as position: fixed, and defaults to hidden.
$(window).scroll(function(){
var yPos = $("body").scrollTop();
var yCheck = $("#c3").position().top;
if (yPos > yCheck && !$("#menu").is(":visible"))
{
$("#menu").show();
}
if (yPos <= yCheck && $("#menu").is(":visible"))
{
$("#menu").hide();
}
});
First, get your #section3 top offset and height. Which will be used as the threshold whether #section3 is actually on the window screen.
var top = $('#section3').offset().top;
var bot = topOffset + $('#section3').height();
Then, detect it on your scroll event.
$(window).on('scroll', function () {
var scrollTop = $(window).scrollTop();
if (scrollTop >= top && scrollTop <= bot) {
// #section3 is within the screen.
$('#menu').show();
}
else {
// #section3 is out of screen.
$('#menu').hide();
}
});
This is a common use case, I wrote following code:
// what does "Auto Header" mean, goto https://www.yahoo.com/
// scroll down and you will see the purple part auto fixed to top,
// while when scroll up, it restores and does not be fixed.
// 1. multiple auto header elements handled
// 2. dynamically create/remove elements issue handled
// 3. no unnecessary dom operation, high performance
// usage: just add 'class="auto-header"' to any element you want to auto header
// suggest set each auto-header element specific width and height
// do not guarantee it works when resize or scroll left/right
$(document).ready(function() {
var rawTops = [],
rawLefts = [],
rawStyles = [],
$locations = [], // record next sibling so that element easily find where to restore
fixed = []; // mark whether this element is fixed
$(".auto-header").each(function() {
var $this = $(this),
offset = $this.offset();
rawTops.push(offset.top);
rawLefts.push(offset.left);
rawStyles.push($this.attr("style"));
$locations.push($this.siblings().eq($this.index()));
fixed.push(false);
});
$(window).on("scroll", function() {
$(".auto-header").each(function(i, e) {
if(!fixed[i] && $(window).scrollTop() > rawTops[i]) {
var $te = $(this).clone(true);
$(this).remove();
$locations[i].before($te);
$te.css({
"position": "fixed",
"top": 0,
"left": rawLefts[i],
"z-index": 100
});
fixed[i] = true;
} else if(fixed[i] && $(window).scrollTop() < rawTops[i]) {
$(this).removeAttr("style").attr("style", rawStyles[i]);
fixed[i] = false;
}
});
});
});

Show div after scrolled back to the top

I want to show a Top-Bar, when the user scrolled back to top of the site.
So e.g. the user scrolls down for a minimum of a 300-400px and then when he scrolls back up again to maybe around 100px (left to the top of the site) the bar should toggle / show up.
Thanks for your help! :)
You can add an event listener to document to check when a user scrolls down the page. Once they hit a preset breakpoint, you can remove a hidden class from your navbar element, like so:
var breakpoint = 400;
var navbar = $('.nav-bar');
$(document).scroll(function(){
if($(this).scrollTop() >= breakpoint) {
navbar.removeClass('hidden', 500);
}
});
If your navbar is fixed, you can also check a boolean variable to see if the user has scrolled past the breakpoint, and then set it to true. If they scroll up past the breakpoint, you can then show the navbar, like so:
var breakpoint = 400;
var scrolledPastBreakpoint = false;
var navbar = $('.nav-bar');
$(document).scroll(function(){
if($(this).scrollTop() >= breakpoint) {
scrolledPastBreakpoint = true;
};
if($(this).scrollTop() < breakpoint && scrolledPastBreakpoint) {
navbar.removeClass('hidden', 500);
};
});

Auto Scroll To A each div or element

I need some help regarding auto scroll to each div or element when the user will use the scroll button in the mouse. Here goes the scenario
Suppose this is my structure of the page..
<div id="main-wrap">
<div class="my-div-1">
<p>here goes my content 1</p>
<img src="/images/sample-1" alt="sample-1"/>
</div>
<div class="my-div-2">
<p>here goes my content 2</p>
<img src="/images/sample-2" alt="sample-2"/>
</div>
<div class="my-div-3">
<p>here goes my content 3</p>
<img src="/images/sample-3" alt="sample-3"/>
</div>
</div><!-- end of main-wrap id -->
-Now suppose my each div has got enough content to make the page long. Suppose the user is on my-div-1 and when the viewer uses the scroll button to scroll down, instead of scrolling through the whole div, i want it to scroll automatically to the my-div-2.
I hope my explanation make sense here.
Is there any way to sort it out by using javascript and jquery?
I will appreciate any response..Thanks in advance.
Here's a fiddle with what you want: http://jsfiddle.net/3qxhY/9/
Source of plugin used in code (debounce/throttle plugin): http://benalman.com/projects/jquery-throttle-debounce-plugin/
Code
// debounce/throttle plugin
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);
//elements you want to scroll to go here
divs = [$(".my-div-1"),$(".my-div-2"),$(".my-div-3")];
var lastScrollTop = 0; //we'll update this on every scroll and compare it to the last scroll to determine the scroll direction
var run = true;
$(window).scroll($.debounce(250, true, function () { //debounce so it only runs once per scroll
var st = $(window).scrollTop();
if (st > lastScrollTop) { // if the scrollTop when the scroll event fires is larger than the last scroll, we can assume the scroll was in a downward direction
$.each(divs, function (i, v) {
((v.offset().top - $(window).scrollTop()) < 0) && (next = i + 1); //compare each elements offset to the windows offset to determine which element we're currently scrolling through
});
run = (next != divs.length) ? true : false; //dont run if we are at the last div
} else {
$.each(divs, function (i, v) {
((v.offset().top - $(window).scrollTop()) < 0) && (next = i);
});
run = true;
}
if (run) {
$('html, body').animate({
scrollTop: divs[next].offset().top
}, 1000,'linear', function() {
lastScrollTop = $(window).scrollTop();
});
} else { lastScrollTop = $(window).scrollTop(); }
}));

Update scroll position on resize of window

I'm currently using a combination of smooth scroll and IDs/anchor tags to scroll to content on my site. The code below is getting the ID of the next 'section' in the DOM, and adding it's ID as the 'view next section' href, so once it's clicked, it'll scroll to the top of that div. Then, it iterates through, updating the href with the next ID each time etc until the last section is seen and it scrolls back to the top. Pretty straightforward.
The only problem is that the 'sections' are fullscreen images, so as it's scrolling to the top of the next section, if you resize the browser, the top position of that section (where we scrolled to) has moved, and means the position is lost.
I've created a JSFiddle. You can see this happening after you click the arrow to visit the next section then resize the window: http://jsfiddle.net/WFQ9t/3/
I'm wanting to keep this top position fixed at all times so even if you resize the browser, the scroll position is updated to reflect this.
Thanks in advance,
R
var firstSectionID = $('body .each-section').eq(1).attr('id');
$('.next-section').attr('href', '#' + firstSectionID);
var i = 1;
$('.next-section').click(function() {
var nextSectionID = $('body .each-section').eq(i).attr('id');
i++;
$('.next-section').attr('href', '#' + nextSectionID);
var numberOfSections = $('body .each-section').length;
var lastSectionID = $('body .each-section').eq(numberOfSections).attr('id');
if ($('.next-section').attr('href') == '#' + lastSectionID ) {
$('.next-section').attr('href', '#introduction');
i = 1;
}
});
Ok, Please check out this fiddle: http://jsfiddle.net/WFQ9t/9/
The few things I did were:
Made some global variables to handle the screen number (which screen you're on and also the initial window height. You will use this when the screen loads and also when you click on the .next-session arrow.
var initWinHeight = $(window).height();
var numSection = 0;
Then I tossed those variables into your resizeContent() function
resizeContent(initWinHeight, numSection)
so that it will work on load and resize
I made the body move around where it needs to, to accomodate for the movement of the divs (I still don't understand what divs are moving when the regular animation happens).
$('body').css({
top: (((windowHeight - initWinHeight)*numSection)*-1) + "px"
});
Then in your click function, I add 1 to the section number, reset the initial window height and then also reset the body to top:0. The normal animation you have already puts the next section at the top of the page.
numSection++;
initWinHeight = $(window).height();
$('body').css({top:"0px"}, 1000);
Finally, I reset the numSections counter when you reach the last page (You might have to make this 0 instead of 1)
numSection = 0;
The fiddle has all of this in the correct places, these are just the steps I took to change the code.
Here is a solution that i found, but I dont use anchor links at this point, i use classes
Here is my HTML code:
<section class="section">
Section 1
</section>
<section class="section">
Section 2
</section>
<section class="section">
Section 3
</section>
<section class="section">
Section 4
</section>
And here is my jQuery/Javascript code,
I actually used a preety simple way:
$('.section').first().addClass('active');
/* handle the mousewheel event together with
DOMMouseScroll to work on cross browser */
$(document).on('mousewheel DOMMouseScroll', function (e) {
e.preventDefault();//prevent the default mousewheel scrolling
var active = $('.section.active');
//get the delta to determine the mousewheel scrol UP and DOWN
var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
//if the delta value is negative, the user is scrolling down
if (delta < 0) {
next = active.next();
//check if the next section exist and animate the anchoring
if (next.hasClass('section')) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: next.offset().top
}, 800);
next.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
} else {
prev = active.prev();
if (prev.length) {
var timer = setTimeout(function () {
$('body, html').animate({
scrollTop: prev.offset().top
}, 800);
prev.addClass('active')
.siblings().removeClass('active');
clearTimeout(timer);
}, 200);
}
}
});
/*THE SIMPLE SOLUTION*/
$(window).resize(function(){
var active = $('.section.active')
$('body, html').animate({
scrollTop: active.offset().top
}, 10);
});

Categories