I have a one pager. And in that one pager, I have an item that is set as display:none (fixed side nav in a div).
Can I have it show when scrolling to a certain div?
So it starts out in the code but not displayed, and then when the user scrolls to #about can the side nav show up?
Essentially you will need to check if the user has scrolled to or beyond the div id of about.
First you will need to establish the current Y value of the div.
//cache about div
var about = $('#about');
//this caches the about div position on window load
var aboutPosition = about.position();
Next you will need to determine how far the the user has scrolled. The best way I have determined to accomplish this is with a timer. You could use the scoll event but its far too taxing on the user browser and a timer will be for the most part indistinguishable.
//generic timer set to repeat every 10 mili(very fast)
//with a callback to execute the logic
var checkScrollPos = window.setInterval("scrollTopLogic()",10);
function scrollTopLogic(){
//if about y position is greater than or equal to the
//current window scroll position do something
if(aboutPosition.y >= $(window).scrollTop()){
$('nav').show();
//remove timer since it is no longer needed
window.clearInterval(checkScrollPos);
}
}
You can catch the scroll event of the div and show the element like this
$("#div").scroll(function() {
$("#item").show();
});
Related
I have a div with id "page-content", it does not have height or width, it just have a blank div.
I'm filling that div with content dynamically, so the div height is growing constantly, I'm making a chat, and i want to detect if I am at the bottom of the div or in the last 10% of the div total height, If true, scroll to the bottom
var box = $('#page-content');
if (box.scrollTop() > (box.height*0.90))
box.scrollTop(25000); // This is the top bottom
What I'm trying to do is, check if you are in the last 10% or less top bottom height of "#page-content" div (not when I'm reading "old messages" at the beginning of the Div), I have a function that appends new messages but I need to scroll down manually to see new messages...so i want to automatically scroll to the New bottom so i can see the new message :)
UPDATE:
function getChat() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<span class="color-'+result.color+'"><b>'+result.usrname+'</b></span> <i class="fa fa-angle-right"></i> '+result.chattext+'<br>';
lastTimeID = result.id;
}
$('#page-content').append(html);
if(html!="")
{
// Here i need to check if the scroll position is in the bottom or in the last 10%
//then this to scroll to the top bottom (25000 is height limit)
$('.page-content').scrollTop(25000);
}
}); }
The trick is that inside the container for your messages (in your case the #page-content DIV), you can have an invisible placeholder div with some id set on to it.
In this demo JSFiddle, as you click on the anchor .addItem, after the new item is added to the container, the placeholder div is moved to the end of the container. This ensures at the same time that clicking on the .addItem brings the bottom of the container DIV into view (as it refers the id of the placeholder in its href attribute).
function scrollToBottom(container) {
// get all the child elements of the container
var children = container.children('.item');
// move the placeholder to the end of the container
$('#contentBottom').insertAfter(children.eq(children.length - 1));
}
Update
In order to determine your current scroll position, you should listen to scroll events in the container. Meanwhile, you should take into account the updated height value of the container when new messages arrive.
Check out this updated fiddle in which I'm checking if the current scroll position is beyond 60 % from the top to easily see the effect.
Note: If a new message comes when you are not scrolling, you can simply do $('.container').scrollTop(25000) in the same function/block of code that appends it to the container.
there is a trick in scrolling the page to bottom of DIV, i tried implementing it in this fiddle.
See $(window).height()+$(window).scrollTop() will always be equal to the total height(including paddings,margins) of children of the window, in our case it is equal to the $('#page-content').height()+margin/padding.
CSS:
div#page-content {
height:600px;
border:solid 1px red;
}
in our situation:
$(window).height()+$(window).scrollTop()=$('#page-content').height()+(margin/padding)=600px
so whenever we scroll it, we can attach an scroll() event to the div and easily check whether we are in in the last 10% or less top bottom height of "#page-content"
$(window).on('scroll',function(){
if($(window).height()+$(window).scrollTop()>=($('#page-content').height()*(.9))){
$(window).scrollTop($('#page-content').height()-$(window).height())
}
})
Good luck.
Since I did not make this, I don't want to take credit for it.
There is a jQuery plugin that makes anything that has a scroll bar scroll to a specific location or to an element. Since you want to scroll to a dynamic div, you can call this after you created the div and it will scroll to that location.
You can find the plugin over here.
You can find a demo of the plugin in action over here.
Hope this was what you are looking for.
-W
I want the class .disabled to be added to the left and/or right controls (.tab-left, .tab-right) if the first or last tab is showing so a user can see that they have reached the end and cannot click any further.
Right now I something like this to prevent the user from going past the end.
if (tabs are at the end) {
return;
}
This works for users not being able to click past the end, but if I add the class before returning, the problem is the .disabled class won't be added until the tabs have reached the end and the user clicks again.
if (tabs are at the end) {
$('.tab-right').addClass('disabled');
return;
}
I need the disabled class to be added when the last tab is showing, not when the user trys to click past the end.
Here's a link to the js fiddle: http://jsfiddle.net/uue6pgcx/
One option you could try is to enable/disable the right and left buttons once the animation is complete.
$ul.filter(':not(:animated)').animate({
"left": dir + liWidth
}, {
complete: function () {
// Calculate the number of items in the container (without left and right navigation buttons).
var lisContainer = Math.round(($container.width() - $left.outerWidth() - $right.outerWidth()) / liWidth);
// Disable right button when list is moved to the left a number of items
// such as the remaining number of them is less or equal than the number
// of items that fit in the container.
$right.toggleClass('disabled', $li.length + $ul.position().left / liWidth <= lisContainer);
// Disable left button when list is in the origin.
$left.toggleClass('disabled', $ul.position().left === 0);
}
});
Disclaimer: According to jQuery outerWidth additional notes, The number returned by dimensions-related APIs, including .outerWidth(), may be fractional in some cases. Code should not assume it is an integer.. So lets hope Math.round will suffice to get the proper number.
Maybe there is a better way to calculate if the right button must be disabled/enabled instead of relying on the number of items that fit in the container.
Here it is your code with the above modification:
http://jsfiddle.net/0Lsepxeu/
I have a list of images on a page. As I scroll through the page I would like to show some options in a naviationbar of the image currently in the viewport. Therefore I need to get the image element currently in the viewport, is this possible ?
Jakob
Who says there's just one image in viewport? What would you like to do when there are many?
But otherwise you can always get the scroll position of your container with images as well as your images' top offset to see which one is currently in-view.
So these values will get you to your result
container scroll position
container visible client height
images' top offset
Using these values will make it possible to locate all images in the view regardless whether they're fully or partially displayed (at the top or bottom).
This is a simplified JSFiddle that gives red border around the first fully-in-the-view image. The code does this:
// get top positions and references to all images
var pos = $("img").map(function(){
var $this = $(this);
return {
el: $this,
top: $this.offset().top
};
}).get();
// provide document scrolling
$(document).on("scroll", function() {
$("img").removeClass("first-in-view");
var scroll = $(this).scrollTop();
var i = 0;
while(pos[i].top < scroll) i++;
pos[i].el.addClass("first-in-view");
}).scroll();
This should be optimised to only toggle class when it needs to. Otherwise we have flickering in every scroll. But it demonstrates how this can be done and you can get going from here.
IMPORTANT
It is utterly important that you attach your image position determining process on document load event and not the usually use DOM ready, because you have to wait for the document to load in order for your images to have final positions.
I'm using the JQuery plugin jScrollPane.
A client has asked me if when a user scrolls the list of items, and clicks on one, then clicks back in their browser or goes back to that page from a menu, can the scroll box be at the same position. :S
This would mean storing the "top" css attribute computed by the plugin into a cookie on mouseUp (when they let go of the slider, store the value of "top") then when they return, I can check for that cookie and set it to that position.
That's the idea anyway, I've no idea even where to be begin with this.
Thanks for any responses. :)
Here's my solution.
The position of the scrollbar is saved to localstorage, then when the page loads again, either by refresh or back from another page, if localstorage has a value greater than 0 which represents the top of the scrollbar (default, unscrolled position), it scrolls to that position.
var element = $(".scroll-pane").jScrollPane({showArrows:true});
if(element != undefined) {
var api = element.data("jsp");
$(function() {
if(parseInt(localStorage.getItem("ScrollPosition")) > 0) {
api.scrollToY(parseInt(localStorage.getItem("ScrollPosition")))
}
$(".scroll-pane").bind("jsp-scroll-y", function(event, scrollPositionY, isAtTop, isAtBottom) {
localStorage.setItem("ScrollPosition", scrollPositionY)
}).jScrollPane()
})
}
;
I'm implementing keyboard controls on my website that allow the user to move down to the next div (that has the class "post"), as well as up to the previous div, with the keyboard arrow keys.
I can bind a function to the keypress just fine, I just need some help with the javascript (i'm using jquery) that determines which div is the next / previous.
It's important that if the user scrolls halfway down the screen with the standard scrollbar, the next item is whatever is next, relative to the top of their viewing window, so I know I need to calculate the next/previous divs using the users current scroll position.. but I'm a bit lost on how to do that.
Firstly, you're going to have to test for the current scrollbar position with $(document).scrollTop().
Once you have that, you can iterate over your elements using $(".post").each(), comparing their top offset to the scrollbar position. If it's lower than the scrollbar, that is your next element, so break out of the loop with return false.
Full example:
var scrollPosition = $(document).scrollTop(),
nextPost = 0,
currentPosition = 0;
$(".post").each(function() {
currentPosition = $(this).offset().top;
if (currentPosition > scrollPosition) {
nextPost = currentPosition;
return false; // break the loop
}
});
$(document).scrollTop(nextPost); // Scrolls the page to the post