jQuery | Keep top div element in view while window scrolling - javascript

I have a div element with class .b-widget and is present on the top of the page.
When I scroll down, the div goes away and when I scroll up it appears again.
I want it to stick to its place when i scroll down and resume when I scroll up.
I wrote below script but this is not helping either :
<script>
//keep element in view
(function($)
{
$(document).ready( function()
{
var elementPosTop = $('.b-widget').position().top;
$(window).scroll(function()
{
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
//if top of element is in view
if (wintop > elementPosTop)
{
//always in view
$('.b-widget').css({ "position":"fixed", "top":"50px" });
}
else
{
//reset back to normal viewing
$('.b-widget').css({ "position":"inherit" });
}
});
});
})(jQuery);
</script>

use css like this:
.b-widget{
position: fixed;
width: 100%;
top: 0;
left: 0;
}

Related

Lazy Load and infinitive scrolling issue in jQuery to find new height of an element with position absolute?

I have a div element with position absolute and overflow scroll like this:
<style>
.sevencov {
position: absolute;
width: 61.333%;
left: 16.667%;
top: 46px;
bottom: 0;
right: 0;
overflow: auto;
}
</style>
<div class="sevencov">
<a id="load-more" class="load-more" title="Load More" onclick="myFunction()"></a>
</div>
I want to fire the load more button at a certain % of the div on scroll, using jQuery I tried this:
$(function () {
var prevHeight = $('.sevencov').height();
$('.sevencov').scroll(function () {
var curHeight = $(this).height();
if ($(this).scrollTop() > ($(document).height() - curHeight)*44) {
$('#load-more').click();
}
});
});
But the problem is that it fires multiple times because the height of my div sevencov is always the same and I'm not able to find a solution, what am I doing wrong?
This is called as Lazy Loading
You can play with scrollTop, innerHeight and scrollHeight as below.
Documentation
scrollTop - Get the current vertical position of the scroll bar for the element
innerHeight - Get the current computed inner height (including padding but not border) for the element
scrollHeight - The height of an element's content, including content not visible on the screen due to overflow
In the below snippet, you can place your ajax call.
Also, the below snippet had window.loadProfile = loadProfile; to make sure your inline onclick works with the parameters onClick="loadProfile(184, '', 'user69')". If possible, you can replace this with jquery click event like, $('#load-more').on('click', function(){ /* ajax call */ });
$(function () {
var testContent = 'The quick brown fox jumps over the lazy dog. ';
var increment = 20;
var contentLoading = false;
var sevencovDiv = $('.sevencov');
function loadProfile(id, text, user) {
// You can do a ajax call here instead of a below code
for(var i = 0; i < increment; i++) {
sevencovDiv.html(sevencovDiv.html() + testContent);
}
contentLoading = false; // make this false once the content loaded from ajax call
}
loadProfile();
window.loadProfile = loadProfile;
$('.sevencov').scroll(function () {
if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
if(!contentLoading) {
//loadMore();
contentLoading = true;
$('#load-more').click();
}
}
});
});
.sevencov {
position: absolute;
width: 61.333%;
left: 16.667%;
top: 46px;
bottom: 0;
right: 0;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sevencov">
<a id="load-more" class="load-more" title="Load More" onClick="loadProfile(184, '', 'user69')"></a>
</div>
As mentioned in another question (here), to get the height of a overflow element, you should use $('.sevencov')[0].scrollHeight instead of .height()

Change Image's Position based on scrollTop

I have a back to top image that popups when the user scrolls beyond 280. The issue is when you reach the bottom the image is over links in the footer. So I want to change the position of the image once the user is about 90px from the very bottom of the page - I want "bottom": '35px' to be 95. The page height is always changing fyi. Code I have:
function update() {
if ($(window).scrollTop() > 280) {
$('#btt').animate({
"bottom": '35px'
}, 300);
}
else {
$('#btt').animate({
"bottom": '-80px'
}, 300);
}
}
setInterval(update, 500);
It might be better to check for the scroll position only when the page has been scrolled rather than just checking every 1/2 second.
I've put together a working demo of what I think you want here: http://jsfiddle.net/swpqpv4r/5/
Basically we need to look at the scroll position of the bottom of the window as we scroll instead of the top by using document.body.scrollTop + $(win).height(). Normaly we might want to worry about what could happen if the window were to be resized, but we calculate this each time inside of the scroll event, so it shouldn't be an issue if the window changes sizes.
Next we need to know when the top of the footer has scrolled above the bottom of the window. We can use $("#footer").position().top; to see where it's top position is.
Hopefully the code is commented enough to help explain it. Let me know if you have any questions.
HTML
<header>Top</header>
<br><br><br> <!-- Lots of these for testing -->
<footer id="footer">Bottom</footer>
<a id="btt" href="javascript:{};">Back to top</a>
JavaScript
$(function(){
//select once and re-use later
var $win = $(window);
var $btt = $("#btt");
var $foot = $("#footer");
var bttDisplay = 500;
var footerHeight = $foot.outerHeight();
var footerTop = $foot.position().top;
function updateScroll() {
var scrollBottom = document.body.scrollTop + $win.height();
if (scrollBottom >= bttDisplay && scrollBottom <= footerTop) {
//show it by setting the bottom position to 0
animateBtt(0);
}else if (scrollBottom >= footerTop) {
//move it up above the footer's top position
animateBtt(footerHeight);
}else {
//hide it by setting the bottom position to the negative value of it's height
animateBtt($btt.height() * -1);
}
}
function animateBtt(pos){
$btt.animate({
"bottom": pos
}, 300);
}
//run initially
updateScroll();
//Create a var to hold the timer
var scrollTimer = null;
$win.on("scroll",function(ev){
//when scrolling, clear the timer
clearTimeout(scrollTimer);
//Now set the timer to run a function after a small delay.
//This prevents the update from happening too many times when you scroll
scrollTimer = setTimeout(updateScroll, 50);
});
//click to scroll back up
$btt.on("click",function(){
$('html, body').animate({scrollTop:0},300);
})
});
CSS
html,body{
margin:0;
padding:0;
}
header, footer{
background: #CCC;
padding: 10px;
}
#btt{
position:fixed;
height: 30px;
width: 100px;
text-align:center;
bottom: -30px;
right:0;
background: #F00;
color: #FFF;
z-index: 1000;
}

Detect users position on web page

Let's say I have a single HTML page. 2000 pixels long for example. I want to detect if a visitor reaches a certain point on the page.
The page structure:
0px = begin of the page;
500px = about us page;
1000px = contactpage;
Is there a way with jQuery to detect if a user reaches the points described above?
You probably want jQuery's scroll event-binding function.
Yes, I would create three divs and then have a mouse over event on each. Example:
$("#begin").mouseover(function(){
alert("over begin");
});
$("#about").mouseover(function(){
alert("over about");
});
$("#contact").mouseover(function(){
alert("over contact");
});
You can see a working fiddle here: http://jsfiddle.net/ezj9F/
Try THIS working snippet.
Using this code you don't have to know position of the element you want to check if it is visible.
JQuery
var $window = $(window);
// # of pixels from the top of the document to the top of div.content
var contentTop = $("div.content").offset().top;
// content is visible when it is on the bottom of the window and not at the top
var contentStart = contentTop - $window.height();
// content is still visible if any part of his height is visible
var contentEnd = contentTop + $("div.content").height();
$window.scroll(function() {
var scrollTop = $window.scrollTop();
if(scrollTop > contentStart && scrollTop < contentEnd) {
console.log('You can see "HELLO"!');
} else {
console.log('You cannot see "HELLO"!');
}
});
HTML
<div class="scroll"></div>
<div class="content">HELLO</div>
<div class="scroll"></div>
CSS
div.scroll {
background-color: #eee;
width: 100px;
height: 1000px;
}
div.content {
background-color: #bada55;
width: 100px;
height: 200px;
}
EDIT: Now the algorithm is checking if any part of the div.content is visible (it is considering height of the element). If you are not interested in that change contentEnd to var contentEnd = contentTop.

Change Div Y Position with mouse wheel and sidebar

I need that when I scroll down or up with mouse wheel or sidebar my div change incrementally the Y position (for example 50px up or down ). I need this in Javascript/Jquery.
I Try this code, but only works for scrolling down(The Scrolling Down and Up Function is working well, only the animate part is working wrong):
UPDATE:
var sidebarScrollTop = 0;
$(document).ready(function() {
sidebarScrollTop = $("body").offset();
$(window).scroll(function ()
{
var docScrollTop = $('body,html').scrollTop();
if(docScrollTop > sidebarScrollTop.top)
{
$("#legend").stop().animate({ marginTop: "+=50px",}, 'slow', "easeOutCirc" );
}
else
{
$("#legend").stop().animate({ marginTop: "-=50px",}, 'slow', "easeOutCirc" );
}
});
});
$(window).resize(function()
{
sidebarScrollTop = $("#legend").offset().top;
});
$(document).resize(function()
{
sidebarScrollTop = $("#legend").offset().top;
});
Thanks
You can use
$(window).scroll(function() {
// Your scroll code here
});
to grab whenever the user is scrolling on the page.
Next you want to change the div's y-value.
If the div is positioned absolute, this is just changing its top-value.
$('my-div').top = original-top-value + $(window).pageYOffset;
I believe you need is to keep the div always showing even when user scrolls down. If that is the case then it can be done with only CSS:
div {
position: fixed;
z-index: 100;
top: 100px;
left: 100px;
}
The values of z-index, top and left are dummy values. Change em with your ones.
UPDATE:
Since CSS Solution won't work for you, here is a working example writter in JS: http://jsfiddle.net/qCtt5/

Position fixed related parent container

I need solution to emulate fixed position, but relative parent div, not whole viewport. JS solutions are laggy. I need fixed related parent container, because if window has small height, div with fixed position enters into footer zone.
Example
Another approach re your update.
Try giving the fixed div z-index: 10;
And the footer div position: relative; z-index: 11
That should make the footer overlap the fixed div.
then it's not an issue of position:fixed, maybe you could just define a min-height to your body (or on the main wrapper if any) to avoid the short page problem
I have combined css and js:
$(document).ready(function () {
var $sidebar = $(".register-box"),
$window = $(window),
$content = $("#content"),
docHeight = $(document).height();
var entered = false;
$window.scroll(function () {
if ($window.height() < 795 && docHeight - $window.scrollTop() < 785) {
entered = true;
var pos = $sidebar.offset();
$sidebar.css('position', 'absolute').css('top', ($content.height() - ($sidebar.height() + 40)) + 'px');
}
else {
if (entered) {
entered = false;
$sidebar.css({
top: "",
left: "",
position: "fixed"
});
}
}
});
});
Code is not final, and numbers are hard coded, but it works, smooth enough.

Categories