Scroll to navigation only working from first element - javascript

I am a beginner in javascript and can't quite grasp what I need to change to make this work.
This is the link.
I have a container with a collapsable fixed navigation. You should be able to click on each of the nav items and scroll to the chapter. The thing is: it only works coming from the top or 'Chapter 1'.
When I click on a nav chapter twice it goes up and down and doesn't just simply go to its anchor.
This is the javascript that I found when I had it set up without a fixed navigation — what to change for it to work the way I want?:
function scrollNav() {
$('.nav a').click(function(){
//Toggle Class
$(".active").removeClass("active");
$(this).closest('li').addClass("active");
var theClass = $(this).attr("class");
$('.'+theClass).parent('li').addClass('active');
//Animate
$('#container').stop().animate({
scrollTop: $( $(this).attr('href') ).offset().top - 180
}, 400);
return false;
});
$('.scrollTop a').scrollTop();
}
scrollNav();
Thanks a lot!

See this updated fiddle. I added jquery library, and a console for debugging.
There were two main problems I spotted:
First, use .position() instead of .offset() here. Offset is always relative to the document, while position is relative to the offset parent (which may or may not be the document). See this answer. Since you're interested in the position relative to the parent container, it's .position().top that you should use.
Once that's in place, it's easier to reason about the correct value of scrollTop. When you've scrolled past the target element, its position relative to the #container will be negative. If the chapterPosition is -300 and the current scrollTop is 1000, we want to scroll to 700.
Note, however, that this is because the #container div is fixed-position. In the fiddle above, I put in an alternate way to calculate scroll, if you didn't want sticky headers & so didn't need #container to be fixed.

Related

Scrolling to bottom elements of a page

I have prepared a pretty self-explaining jsfiddle:
http://jsfiddle.net/nt7xzxur/ with the following scrolling code inside:
function smoothScroll(hash) {
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 750);
When you click on one of the links available, the browser's window is scrolled to the point where the corresponding item on the right side is located. There's one thing I would like to achieve though:
Obviously last two items won't scroll up to the top because there's not enough content below them for scrolling. I would like for ALL items to be scrollable to the top and so far I haven't found a good way to do it. I could add some blank lines below the last item, but it adds length to the right scroll bar and is not very elegant.
Is there any other way to make it happen through css, js or otherwise?
You can dynamically calculate the extra space and add this to end of the page. I have created one small code you can look at it and use it according to your need http://jsbin.com/mubugusido/6/edit?html,js
This will add extra space at the bottom of your .main div:
wH = $(window).height();
$extraH = $('<div></div>').height(wH);
$('.main').append($extraH);
Or you could add a min-height to .main and set it to some amount to guarantee there's enough space.
I believe that the only way you can achieve this is to actually add some content at the bottom.
You cannot get the page to scroll to the top of the Fifth Item because there isn't anything below to display, because the page has ended.

Jquery scroll function for nested <div>

I'm trying to make a nav that scrolls to a corresponding <div> for my site. The corresponding divs are nested inside another div with a max-height and scrollbar. That's when my jquery tends to fail me.
He's a fiddle from another question that I related to my problem: JSFIDDLE
Notice when you click the button, it doesn't scroll to the correct div, and it scrolls to an awkward position when clicked again.
How do I get it to scroll to the correct div and not strangely scroll back when it is clicked again? Thanks!
$(".third").offset().top) alternates coordinates between 1108 and 0 when clicked. These are the correct positions of .third before each click. You have to take into account the current scroll position and the position of the .first div.
Replace the scrollTop line of code with the following:
scrollTop: $(".third").position().top - $('div.nest').position().top + $('div.nest').scrollTop()},
http://jsfiddle.net/pyL62v58/3/
The Code works, it seems to be a padding/margin issue.
Just add this line in the css, and it should work:
* {paddin:0;margin:0}
/* tested on Chrome 39+ on Win7 */
here the Updated fiddle
Why it jumps up again, is hopefully clear. Documentation to the "offset" function can be found here: jQuery-Doc

Using jQuery to detect scroll distance from the top of a div, not from top of page

So here's the deal. I have a div (call it div.container for troubleshooting purposes) on my page that will hold dynamically loaded content from a database (loaded using PHP). I want to detect the user's scroll position from the top of div.container, not from the top of the page. Note, div.container is not positioned at the top of the page, but is a child div with a position roughly 50px from the top of the page. I am looking to get the scroll distance in pixels.
I tried this with zero success:
$("div.container").scrollTop();
Other than that, I really have no idea where to start with this. Any help is so greatly appreciated. Thanks much.
You need to get the window's scrollTop() and subtract the '.container' offset() top value:
$(window).scroll(function(){
var posTop = $(window).scrollTop() - $('.container').offset().top
});
See this jsfiddle demo.
use the offset to caculate the child div 's distance from the parent div,

Anchor Link With Two Fixed Navigations - Complex

Basically I have a fixed header with a navigation in it that is always attached to the top of the window. Then I have another fixed element which is a Pagination but its only attaches its self to the top of window when its is scrolled to!
This pagination has anchor links that link to different sections on the page! However when you click on the links it covered the content which both fixed floating elements.
Here is the example: http://www.chudz.co.uk/test/
If you scroll down you will see the pagination attach itself to the header navigation! Then if you click on "A" in the pagination you will see what happens! The content gets covered! (A is the only link that works atm sorry).
Anyone know of a solution I could use?
Thanks
Here is the JavaScript work around for this problem.
First, change the name attribute to id attribute in the head links like this.
<h2><a id="a">Authors - A</a></h2>
Then add this script into your bottom script.
$(document).ready(function(){
$("#pagination a").click(function(event){
event.preventDefault();
var o = $( $(this).attr("href") ).offset();
var sT = o.top - 151; // 151 is the header height + navigation height
window.scrollTo(0,sT);
});
});
Your fixed pagination is not taking up any space in the dom.
You should use 'id' instead of 'name', then add a class to the anchor, position it absolutely and move it upwards with a negative margin (the same as the height of the pagination). This will ensure that the anchor starts below the pagination.

How to scroll to an element in jQuery?

I have done the following code in JavaScript to put focus on the particular element (branch1 is a element),
document.location.href="#branch1";
But as I am also using jQuery in my web app, so I want to do the above code in jQuery. I have tried but don't know why its not working,
$("#branch1").focus();
The above jquery (focus()) code is not working for div, whereas If i am trying the same code with textbox, then its working,
Please tell me, how can I put focus on a div elemnt using jQuery?
Thanks!
For my problem this code worked, I had to navigate to an anchor tag on page load :
$(window).scrollTop($('a#captchaAnchor').position().top);
For that matter you can use this on any element, not just an anchor tag.
Like #user293153 I only just discovered this question and it didn't seem to be answered correctly.
His answer was best. But you can also animate to the element as well.
$('html, body').animate({ scrollTop: $("#some_element").offset().top }, 500);
You can extend jQuery functionalities like this:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 500);
}});
and then:
$('...').scrollToMe();
easy ;-)
Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.
Check out jquery-scrollintoview.
ScrollTo is fine, but oftentimes you just want to make sure a UI element is visible, not necessarily at the top. ScrollTo doesn't help you with this. From scrollintoview's README:
How does this plugin solve the user experience issue
This plugin scrolls a particular element into view similar to browser
built-in functionality (DOM's scrollIntoView() function), but works
differently (and arguably more user friendly):
it only scrolls to element when element is actually out of view; if element is in view (anywhere in visible document area), no scrolling
will be performed;
it scrolls using animation effects; when scrolling is performed users know exactly they're not redirected anywhere, but actually see
that they're simply moved somewhere else within the same page (as well
as in which direction they moved);
there's always the smallest amount of scrolling being applied; when element is above the visible document area it will be scrolled to the
top of visible area; when element is below the visible are it will be
scrolled to the bottom of visible area; this is the most consistent
way of scrolling - when scrolling would always be to top it sometimes
couldn't scroll an element to top when it was close to the bottom of
scrollable container (thus scrolling would be unpredictable);
when element's size exceeds the size of visible document area its top-left corner is the one that will be scrolled to;
Use
$(window).scrollTop()
It'll scroll the window to the item.
var scrollPos = $("#branch1").offset().top;
$(window).scrollTop(scrollPos);
If you're simply trying to scroll to the specified element, you can use the scrollIntoView method of the Element.
Here's an example :
$target.get(0).scrollIntoView();
I think you might be looking for an "anchor" given the example you have.
This link will jump to the anchor named jump
<a name="jump">This is where the link will jump to</a>
The focus jQuery method does something different from what you're trying to achieve.
For the focus() function to work on the element the div needs to have a tabindex attribute. This is probably not done by default on this type of element as it is not an input field. You can add a tabindex for example at -1 to prevent users who use tab to focus on it. If you use a positive tabindex users will be able to use tab to focus on the div element.
Here an example: http://jsfiddle.net/klodder/gFPQL/
However tabindex is not supported in Safari.
maybe you want to try this simple one
$(document).ready(function() {
$(".to-branch1").click(function() {
$('html, body').animate({
scrollTop: $("#branch1").offset().top
}, 1500);
});
});

Categories

Resources