Add an anchor to scrollTop - javascript

Is it possible to add an anchor to this script? Instead of scrolling all the way to the top, I would like to scroll to a particular anchor in the page.
Here is the current script:
if (isError) {
$('html, body').animate({
scrollTop: 700
}, 2500);
$("#error-div").show();
} else {
$("#error-div").hide();
}

There's not really the need to include a huge plugin for this simple task.
With jQuerys position() - function (jQuery Doc) you can get the position of an element in the DOM (as long as it's visible). It returns an object with a top and left - value, relative to the parent. If you want values relative to the document, use the offset() - function, usage stays the same.
I created a little fiddle to show you the basic usage:
http://jsfiddle.net/DtADS/

Use the scrollto plugin, you can scroll the entire page to any element, or even scroll inside of elements. http://demos.flesler.com/jquery/scrollTo/

If I understood your question, you need to place something like that on the place in your page you want to scroll <div id="scrollHere"></div> and in your jquery:
window.location.href = "#scrollHere";
this method goes the page right where the #scrollHere rest, if that the case.

Related

Prevent window scroll below fold until button click

I have a situation where I need the page to not be scrollable past a certain point (I have the hero set to 100vh and the user should not be able to scroll at all) and then upon click of a button the scroll prevention is disabled and the user is then automatically smooth scrolled down to an anchor link directly below (basically scroll down 100vh or the full window height). I need a smooth scrolling animation instead of just a quick jump.
I've tried playing around with variations of the following code with no luck. So far it is really buggy and jumps around and when you reload the page the body overflow is set to hidden but the window position is not always at the top of the screen so you still see some of the below the fold content but still cant scroll.
function() {
function smoothScroll(){
windowHeight = $('window').height();
$('html, body').stop.animate({scrollTop: windowHeight}, slow);
}
$('.bottom-nav').on('click', '.fold-trigger', function(event) {
$('.home').css('overflow', 'visible');
setTimeout(smoothScroll(), 1000);
});
};
Fiddle is here: https://jsfiddle.net/njpatten/yxkvnymu/1/
Fixed Code
function smoothScroll(){
windowHeight = $(window).height();
$('html, body').stop().animate({scrollTop: windowHeight}, "slow");
}
$('.bottom-nav').on('click', '.fold-trigger', function(event) {
$('.home').css('overflow', 'visible');
setTimeout(smoothScroll(), 1000);
});
Fixed fiddle: https://jsfiddle.net/yxkvnymu/2/
Explanation
You are trying to get the window height by doing $('window').height() which is searching for a 'window' DOM element which doesn't exist. You want to use $(window).height() (note the omission of quotes surrounding window) because window is not a DOM node, it is an object.
In addition, you are using $('html, body').stop.animate({scrollTop: windowHeight}, slow); which has multiple errors. .stop is invalid because the stop property on the NodeList that is returned from $('html, body') is a function that you want to call. You should be using $('html, body').stop().
Also, the animate portion is referencing a variable slow. jQuery's animate function takes "slow" as a string, so that line should be written as such:
.animate({scrollTop: windowHeight}, "slow");
Note the inclusion of quotes on that because we want to pass a string value of "slow" to jQuery's animate function, instead of a variable slow.
Lastly, you are surrounding all of your code in an anonymous function, which seems unnecessary.

Scroll to div on clicking the div

Here is the fiddle link https://jsfiddle.net/hitech0101/5vhdm5hy/
$('.block').click( function () {
$('#mainContainer').animate({'width':'20%'}, 1000);
$(this).css({'background-color':'blue'});
$('.block').css({'display':'block','width':'100%'});
$('.second').css({'display':'inline-block'})
});
In the fiddle, i am using jquery to convert the horizontal blocks into vertical blocks. I have changed the block color from red to blue when the block is clicked. When i click a particular block i would the scroll to move to the location of the block in the vertical view. I have tried jquery's scrollTop() method but still could not get it working the way i wanted it to. Please help.
The fiddle is partial representation of the webpage i am working on. There is more content on the original page which i have excluded. The maincontainer is the second container on the page.
No JavaScript necessary. You can specify an element in an anchor's href and it'll scroll it to the top of the window, including itself.
Wrap the div in an anchor or just use the anchor tag itself, they're both wrappers.
<a href="#scrollToMe">
<div id="scrollToMe"></div>
</a>
Just remember that it can only scroll the element into view to the best of its ability, if the item is at the bottom of the parent element the scroll will hit the bottom and it won't be able to go any further.
$(this).get(0).scrollIntoView();
Add this line into the .click function.
Fiddle
I suggest you get the offset top value and animate the #maincontainer to that position
$('.block').click( function () {
$('#mainContainer').animate({'width':'20%'}, 1000);
$(this).css({'background-color':'blue'});
$('.block').css({'display':'block','width':'100%'});
$('.second').css({'display':'inline-block'});
/*below is what i was talking about*/
var pos = $(this).offset();
$('#mainContainer').animate({ scrollTop: pos.top });
});
$(document).on("click", ".block", function() {
var _body_html = $('html, body');
var _scroll_to = $('.scroll-to');
var _top = _scroll_to.offset().top;
_body_html.animate({
scrollTop: _top
}, 1000);
setTimeout(function() {
_body_html.finish();
}, 1000);
});

Scroll to link with skrollr

I am using https://github.com/Prinzhorn/skrollr to animate the background of my site as I scroll. However I am also wanting to have my links scroll up and down the page like a normal single page site would do.
The problem is that both are working if I manually scroll the background changes, if I click the link the page scrolls to the correct place. The problem is that when I click the button the background doesn't scroll as well.
It seems like I am working with two different scroll functions and as a result they aren't working together and I need to use the same one.
Here is the code.
js - Scroll to link:
var $root = $('html, body');
$('a').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
js – Skrollr init
skrollr.init({
smoothScrolling: true,
forceHeight: true
});
I will try put together a fiddle to make it more clear but hopefully the answer is really simple.
If anyone else ever faces this problem the answer lies her: https://github.com/Prinzhorn/skrollr-menu
This will allow you to scroll to you internal links along with Skrollr animations. A HUGE plus and a very simple fix, you don't even need any of your own scrolling code just this and it will work with you links.
There's a way to do this, Skrollr has some methods very useful, in console, just type the variable contains skrollr, it will show some methods that you can use, one of them is "setScrollTop(int, bool)", so just call this method with the info you need, for example:
s.setScrollTop(9000, true)
Which means that I want it to scroll to the height position 9000. It works fine, you just need to know the height position where you need to go.

Scroll a div vertically to a desired position using jQuery

This is a followup question for this:
Scrollpane on the bottom, css is hacky, javascript is hard
I ended up doing the scrolling in the same way explained in the accepted answer.
Now there is a request that one item is selected somehow (eg. as an url parameter or by some javascript calls) I should scroll the pane to the item with the corresponding ID in the scrollpane. Like a link to an anchor () would work!
I want to make a javascript call like this
function scrollTo(id) {
$('#middle').magicallyScrollThatItemWouldBeVisible(itemid);
}
But this is not in jQuery (or at least I don't know of it). So is there a way to make it?
I'll post a simple jsFiddle here:
http://jsfiddle.net/ruisoftware/U6QdQ/4/
Help me write that scrollTo function!
A .animate would be fine too.
UPDATE: If it was not clear I would like it to only align to the left or right side of the panel, it it was overflowed on that side (so the minimum possible amount of scrolling happens)
It's not jQuery, just JavaScript, and I've actually never used it all, so I'm not sure how you would have to mess with it to get it to work in this situation, but there is a scrollIntoView function:
yourElement.scrollIntoView();
Since the elements have a fixed width, you can count the number of elements by using .index() + 1, and animate to this value (after subtracting the container's width).
If you want the element to be centered, use - Math.round(middle.width()/100)*50.
Fiddle: http://jsfiddle.net/U6QdQ/17/
//This code should be run on load / DOMReady
(function($){ //Run on load / DOMReady
$.fn.magicScrollTo = function(){
var middle = $("#middle");
var currentScrollLeft = middle.scrollLeft();
var width = middle.width();
var newScrollLeft = this.offset().left + currentScrollLeft - middle.offset().left;
if(newScrollLeft >= currentScrollLeft && newScrollLeft <= currentScrollLeft + width - this.outerWidth()) return;
if(newScrollLeft > currentScrollLeft){ //If the element is at the right side
newScrollLeft = newScrollLeft - width + this.outerWidth();
}
middle.animate({
scrollLeft: newScrollLeft,
}, 'fast')
}
})(jQuery);
Usage:
//Select the 4rd element, and scroll to it (eq is zero-based):
$('.item').eq(3).magicScrollTo();
Something along these lines would be a good start:
http://jsfiddle.net/vHjJ4/
This will bring the target into the centre of the carousel. I think you will have to add in some extra checks to make sure that it didn't scroll to far, for example if you targeted the first or last element...unless this is built into the scroll function (it might be).
I'm not sure I understand your question exactly, but it sounds like you're asking how to scroll horizontally to the selected item in the bottom pane. If so, try something like this:
//get the position of the element relative to the parent ("middle")
var pos = $("#itemid").position();
if (pos){
$("#middle").scrollLeft(pos.left);
}
From here, you can use the width of middle to center the item if needed.

JavaScript to scroll long page to DIV

I have a link on a long HTML page. When I click it, I wish a div on another part of the page to be visible in the window by scrolling into view.
A bit like EnsureVisible in other languages.
I've checked out scrollTop and scrollTo but they seem like red herrings.
Can anyone help?
old question, but if anyone finds this through google (as I did) and who does not want to use anchors or jquery; there's a builtin javascriptfunction to 'jump' to an element;
document.getElementById('youridhere').scrollIntoView();
and what's even better; according to the great compatibility-tables on quirksmode, this is supported by all major browsers!
If you don't want to add an extra extension the following code should work with jQuery.
$('a[href=#target]').
click(function(){
var target = $('a[name=target]');
if (target.length)
{
var top = target.offset().top;
$('html,body').animate({scrollTop: top}, 1000);
return false;
}
});
How about the JQuery ScrollTo - see this sample code
You can use Element.scrollIntoView() method as was mentioned above. If you leave it with no parameters inside you will have an instant ugly scroll. To prevent that you can add this parameter - behavior:"smooth".
Example:
document.getElementById('scroll-here-plz').scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
Just replace scroll-here-plz with your div or element on a website. And if you see your element at the bottom of your window or the position is not what you would have expected, play with parameter block: "". You can use block: "start", block: "end" or block: "center".
Remember: Always use parameters inside an object {}.
If you would still have problems, go to https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
There is detailed documentation for this method.
Click here to scroll
<A name='myAnchorALongWayDownThePage"></a>
No fancy scrolling but it should take you there.
The difficulty with scrolling is that you may not only need to scroll the page to show a div, but you may need to scroll inside scrollable divs on any number of levels as well.
The scrollTop property is a available on any DOM element, including the document body. By setting it, you can control how far down something is scrolled. You can also use clientHeight and scrollHeight properties to see how much scrolling is needed (scrolling is possible when clientHeight (viewport) is less than scrollHeight (the height of the content).
You can also use the offsetTop property to figure out where in the container an element is located.
To build a truly general purpose "scroll into view" routine from scratch, you would need to start at the node you want to expose, make sure it's in the visible portion of it's parent, then repeat the same for the parent, etc, all the way until you reach the top.
One step of this would look something like this (untested code, not checking edge cases):
function scrollIntoView(node) {
var parent = node.parent;
var parentCHeight = parent.clientHeight;
var parentSHeight = parent.scrollHeight;
if (parentSHeight > parentCHeight) {
var nodeHeight = node.clientHeight;
var nodeOffset = node.offsetTop;
var scrollOffset = nodeOffset + (nodeHeight / 2) - (parentCHeight / 2);
parent.scrollTop = scrollOffset;
}
if (parent.parent) {
scrollIntoView(parent);
}
}
This worked for me
document.getElementById('divElem').scrollIntoView();
Answer posted here - same solution to your problem.
Edit: the JQuery answer is very nice if you want a smooth scroll - I hadn't seen that in action before.
Why not a named anchor?
The property you need is location.hash. For example:
location.hash = 'top'; //would jump to named anchor "top
I don't know how to do the nice scroll animation without the use of dojo or some toolkit like that, but if you just need it to jump to an anchor, location.hash should do it.
(tested on FF3 and Safari 3.1.2)
I can't add a comment to futtta's reply above, but for a smoother scroll use:
onClick="document.getElementById('more').scrollIntoView({block: 'start', behavior: 'smooth'});"
<button onClick="scrollIntoView()"></button>
<br>
<div id="scroll-to"></div>
function scrollIntoView() {
document.getElementById('scroll-to').scrollIntoView({
behavior: 'smooth'
});
}
The scrollIntoView method accepts scroll-Options to animate the scroll.
With smooth scroll
document.getElementById('scroll-to').scrollIntoView({
behavior: 'smooth'
});
No animation
document.getElementById('scroll-to').scrollIntoView();
There is a jQuery plugin for the general case of scrolling to a DOM element, but if performance is an issue (and when is it not?), I would suggest doing it manually. This involves two steps:
Finding the position of the element you are scrolling to.
Scrolling to that position.
quirksmode gives a good explanation of the mechanism behind the former. Here's my preferred solution:
function absoluteOffset(elem) {
return elem.offsetParent && elem.offsetTop + absoluteOffset(elem.offsetParent);
}
It uses casting from null to 0, which isn't proper etiquette in some circles, but I like it :) The second part uses window.scroll. So the rest of the solution is:
function scrollToElement(elem) {
window.scroll(0, absoluteOffset(elem));
}
Voila!
As stated already, Element.scrollIntoView() is a good answer. Since the question says "I have a link on a long HTML page..." I want to mention a relevant detail. If this is done through a functional link it may not produce the desired effect of scrolling to the target div. For example:
HTML:
<a id="link1" href="#">Scroll With Link</a>
JavaScript:
const link = document.getElementById("link1");
link.onclick = showBox12;
function showBox12()
{
const box = document.getElementById("box12");
box.scrollIntoView();
console.log("Showing Box:" + box);
}
Clicking on Scroll With Link will show the message on the console, but it would seem to have no effect because the # will bring the page back to the top. Interestingly, if using href="" one might actually see the page scroll to the div and jump back to the top.
One solution is to use the standard JavaScript to properly disable the link:
<a id="link1" href="javascript:void(0);">Scroll With Link</a>
Now it will go to box12 and stay there.
I use a lightweight javascript plugin that I found works across devices, browsers and operating systems: zenscroll
scrollTop (IIRC) is where in the document the top of the page is scrolled to. scrollTo scrolls the page so that the top of the page is where you specify.
What you need here is some Javascript manipulated styles. Say if you wanted the div off-screen and scroll in from the right you would set the left attribute of the div to the width of the page and then decrease it by a set amount every few seconds until it is where you want.
This should point you in the right direction.
Additional: I'm sorry, I thought you wanted a separate div to 'pop out' from somewhere (sort of like this site does sometimes), and not move the entire page to a section. Proper use of anchors would achieve that effect.
I personally found Josh's jQuery-based answer above to be the best I saw, and worked perfectly for my application... of course, I was already using jQuery... I certainly wouldn't have included the whole jQ library just for that one purpose.
Cheers!
EDIT: OK... so mere seconds after posting this, I saw another answer just below mine (not sure if still below me after an edit) that said to use:
document.getElementById('your_element_ID_here').scrollIntoView();
This works perfectly and in so much less code than the jQuery version! I had no idea that there was a built-in function in JS called .scrollIntoView(), but there it is! So, if you want the fancy animation, go jQuery. Quick n' dirty... use this one!
For smooth scroll this code is useful
$('a[href*=#scrollToDivId]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
var head_height = $('.header').outerHeight(); // if page has any sticky header get the header height else use 0 here
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - head_height
}, 1000);
return false;
}
}
});
Correct me if I'm wrong but I'm reading the question again and again and still think that Angus McCoteup was asking how to set an element to be position: fixed.
Angus McCoteup, check out http://www.cssplay.co.uk/layouts/fixed.html - if you want your DIV to behave like a menu there, have a look at a CSS there

Categories

Resources