I'm trying to find something similar to the excellent Jquery plugin - Viewport Checker but that doesn't rely on scroll events. The reason it can't rely on scroll events is I'm also using Fullpage.js set to "autoscroll:true" which then doesn't actually scroll the page it uses 3D translate to move site around. I was wondering if anyone could point me in the right direction.
The end result of this:
I want to add a few classes onto a <div> when that <div> enters the viewport.
When I was setting up Viewport Checker this is how I had it configured
<script type="text/javascript">
$(document).ready(function() {
$('.slide_main_paragraph_container').addClass("hidden").viewportChecker({
classToAdd: 'visible animated fadeInUp', // Class to add to the elements when they are visible
offset: 100
});
});
</script>
I think the afterSlideLoad event is the way you'd do this.
afterSlideLoad: function(anchorLink, index, slideAnchor, slideIndex){
var $loadedSlide = $(this),
$main = $loadedSlide.find('.slide_main_paragraph_container.hidden');
if ($main.length) {
$main.removeClass('hidden').addClass('visible animated fadeInUp');
}
}
I have a JS feature on the following site that is working just fine in Firefox but not in Safari: http://rossbolger.com/kids/light-stories/
The feature slides out a grid of thumbnails called #image-thumbs when the mouse hovers over the container called #hit-area. It works (at least in Firefox) by first changing #image_thumbs height from '48px' to 'auto', the height is then measured using jQuery's height(). This height is stored in a variable and then using jQuery's css() it is given back to the #image-thumbs when the mouse is over.
The code on the site looks a little something like this:
// Thumbnails Nav Reveal and Hide Scripts
var thumbs_height = 1,
thumbs = $('#image-thumbs'),
thumbs_original_height = thumbs.css('height');
// Slide Up Thumbs
(function revealThumbs() {
// On hover let the thumbs become their full height
$('#image-thumbs #hit-area').hover(function(){ // Mouse over
// Get the unrestricted height of the thumbs
thumbs.css('height', 'auto');
thumbs_height = thumbs.height();
// then put it back to what it was so we can animate it using CSS3 transition
thumbs.css('height', 'inherit');
// delay 0.1s before triggering the change in height (time for the calculations to complete)
setTimeout( function() { thumbs.css('height', thumbs_height ) }, 100 );
}, function(){ // Mouse out
hideThumbs();
});
})();
// Hide thumbs
function hideThumbs(){
thumbs.css('height', thumbs_original_height );
};
The reason for measuring the unrestricted height and passing it back as a pixel value, rather than simply setting the height to 'auto', is to create a sliding effect via CSS3 (i.e. transition: height 0.5s). The transition only takes place if the affected attribute goes from one numeric value to another.
Thanks for any help bug testing this. I haven't even looked at other browsers yet.
All the best,
Laurence
Okay, so I've worked it out...
In the javascript document (scripts.js on the site) there was a function higher up the page calling the hideThumbs() function. So it wasn't working because the variables in hideThumbs() hadn't been declared at that point. Funny that it should still work in Firefox and IE9!
I've moved all this code to a point before that other function and the problem is now resolved. So far I've only done this locally. I'll update the site in the link above later.
What's the equivalent of the following in plain JS?
$(window).scroll(function() { });
I'm also looking to animate scroll, e.g.:
$('html, body').animate({scrollTop:1750}, 'slow');
Should I be using requestAnimationFrame?
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
Are there any examples that trigger an animation once on click and not continuous renders?
Question 1
window.onscroll = function() {
console.log('scrolling');
};
or if your targeted browsers support addEventListener :
window.addEventListener('scroll', function() {
console.log('scrolling');
});
Question 2
In my opinion, if you're just scrolling from one section to a another section of your page, and not having some sort of constantly running scrolling movement, you're fine doing this without using requestAnimationFrame.
You can find good implementations of scrolling to a particular part of the window in pure javascript, I suggest checking out their source(or even using them).
Here's the breakdown...
wrapper (position:relative; overflow:hidden; )
section-container (position:absolute)
multiple child sections
I attach a mousewheel event listener and animate (with easing) the 'top' position of 'section-container'. As this position changes, the 'background-position' of each section moves vertically based on the position of 'section-container's 'top' property (continually updated through a setTimeout()).
All of that works as it should, except as the 'background-position' changes, the image has a bit of a jitter. This doesn't happen if the 'background-attachment' is set to 'fixed'... but I don't want that.
Can anyone explain this, with a possible fix? I continually refer to the https://victoriabeckham.landrover.com/ site and can't figure out what they're doing differently to get theirs operating so efficiently.
You can check this out, i believe its where they do most of the animating:
https://victoriabeckham.landrover.com/js/ScrollAnimator.js?v=471
I would have to say they have some kind of framework that they are using to accomplish this.
EDIT: Sorry didn't see the new answer above mine, seems like a good starting point.
-Ken
If you inspect this website carefully, you will able to use it like landrover site.
You need to use: scrollTo plugin and parallax plugin
And document jQuery should be like this:
$(document).ready(function(){
$('#nav').localScroll(800);
//.parallax(xPosition, speedFactor, outerHeight) options:
//xPosition - Horizontal position of the element
//inertia - speed to move relative to vertical scroll. Example: 0.1 is one tenth the speed of scrolling, 2 is twice the speed of scrolling
//outerHeight (true/false) - Whether or not jQuery should use it's outerHeight option to determine when a section is in the viewport
$('#intro').parallax("50%", 0.1);
$('#second').parallax("50%", 0.1);
$('.bg').parallax("50%", 0.4);
$('#third').parallax("50%", 0.3);
});
Ok. So I figured out my issue was when trying to animate() the 'section-container' on the 'top' property. I was using a "+=" to allow it to increment from its current position. Not a good idea when using 'mousewheel' events. I changed it to a hard-set variable that is continually incremented/decremented.
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