My problem is that the script loads and runs when the site is loaded but want I really what to achieve is that the script runs when the visitors reaches a certain section while scrolling the page.
Dont get the solution as it doesn't contain the relevant information for the number to count to? I havent a clue about javascript so finding it difficult to understand the changes required.
Please could you tell me what javascript I need to include to allow for when the divs are in the viewport and to count to a specific value when in viewport.
I have three divs named "sectionone" "sectiontwo" "sectionthree" with the class "odometer" but with this code only one of them starts rolling. Do you know how I could fix this?
So your script uses setTimeout() to delay the animations. Rather what you can do is detect if the element is in the view port, and if so update the number.
I would try something like this:
Create a method to check if the element is in the viewport.
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
note: this probaly needs way to track if the animation have already happened/is happening to avoid undesirable behavior
Listen to the window for scroll, and when scrolled loop over the sections:
var sectionVals = [789, 459, 459];
$(window).on('resize scroll', function() {
$('.section').each(function() { // notice that here I used the "section" class to identify multiple sections with the odometer
// more code to come
});
});
Inside loop check if section is in viewport:
var sectionVals = [789, 459, 459];
$(window).on('resize scroll', function() {
$('.section').each(function(index) {
// the more code
// if "in view"
if ( $(this).isInViewport(); ) {
// set the innerHTML using the index and sectionVals variable
$(this).innerHTML = sectionVals[index];
}
// end more code
});
});
Hope this gets you going. If you need any more assistance feel free to reach out!
EDIT:
Sorry i didn't have time to test this code so you may have to rework it to implement.
Hi @Kevin-C! Thank you very much for the input. Maybe I should have had put my own knowledgde in Javascript in the original post. I'm not at all good with code but I'm guessing I could find someone doing it for me on freelancer or something similar. Now I know a bit more on which level this problem is on.